Controller does not work in route - angularjs

I would like to add link with controller to route but controller does not work.
I get this:
{{title}}
{{shortTitle}}
{{text}}
If I will put controller only to html also does not work
but when I added script to main controller in Default.html controller working correct
Where I made mistake?
#SSH this not work
$stateProvider
.state('home', {
url: '/',
template: '<div data-ng-include="'Scripts/js_angular_project/website/home/homePage.html'"></div>',
controller: 'homeCtrl'
})
homePage.html
<div>
<h2>{{title}}</h2>
<h3>{{shortTitle}}</h3>
<p>{{text}}</p>
</div>
<script>
app.controller('homeCtrl', function ($scope) {
$scope.title = "Volvo";
$scope.shortTitle = "Volvo";
$scope.text = "example";
});
</script>
#SSH this also does not work
$stateProvider
.state('home', {
url: '/',
templateURL: '/Scripts/js_angular_project/website/home/homePage.html',
controller: 'homeCtrl'
})
homePage.HTML - I remove ng-controller
<div>
<h2>{{title}}</h2>
<h3>{{shortTitle}}</h3>
<p>{{text}}</p>
</div>
<script>
app.controller('homeCtrl', function ($scope) {
$scope.title = "Volvo";
$scope.shortTitle = "Volvo";
$scope.text = "example";
});
</script>
#SSH this not work when I put my code
.html

var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
template: '<div><h2>{{title}}</h2><h3>{{shortTitle}}</h3><p>{{text}}</p></div>',
controller:'homeCtrl'
})
.state('about', {
url: '/about',
template: '<div><h2>{{title}}</h2><h3>{{shortTitle}}</h3><p>{{text}}</p></div>',
controller:'aboutCtrl'
})
});
routerApp.controller('homeCtrl', function ($scope) {
$scope.title = "Volvo";
$scope.shortTitle = "Volvo";
$scope.text = "example";
});
routerApp.controller('aboutCtrl', function ($scope) {
$scope.title = "Volvo2";
$scope.shortTitle = "Volvo2";
$scope.text = "example2";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<div ng-app="routerApp">
<nav class="navbar navbar-inverse" role="navigation">
<ul class="nav navbar-nav">
<li><a ui-sref="home">Home</a></li>
<li><a ui-sref="about">About</a></li>
</ul>
</nav>
<div class="container">
<div ui-view></div>
</div>
</div>
you should put controller name in router and also remove ng-controller = "homeCtrl" from template.
state('home' ,{
url : '/',
templateUrl:'/yourTempalteAddress',
controller:'homeCtrl'
})
and define your app in controller.
var app = angular.module("yourApp",[]);
app.controller('homeCtrl', function ($scope) {
$scope.title = "Volvo";
$scope.shortTitle = "Volvo";
$scope.text = "example";
});

Related

AngularJS Routing ui.router Failed to instantiate module flapperNews

I'm new to AngularJs and am stuck on a tutorial in the Routing section: https://thinkster.io/tutorials/mean-stack/routing-views-with-angular
Error Message:
Uncaught Error: [$injector:modulerr] Failed to instantiate module flapperNews due to:
Error: [$injector:nomod] Module 'flapperNews' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
Prior to this error message I had a later version of angularjs (1.5.7) and it gave me this error - someone suggested online that you change the version. I had this error then:
Uncaught Error: [$injector:modulerr]
Please help me so that I can move on and get back to learning.
Here are my files:
index.html:
<html>
<head>
<title>My Angular App!</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="app.js"></script>
<style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body ng-app="flapperNews">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<!-- rest of template -->
<div ng-repeat="post in posts | orderBy:'-upvotes'">
<span ng-click="incrementUpvotes(post)">&#9650</span>
<span ng-click="decrementUpvotes(post)">&#9660</span>
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</span>
- upvotes: {{post.upvotes}}
</div>
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Title"
ng-model="title"></input>
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Link"
ng-model="link"></input>
</div>
<button type="submit" class="btn btn-primary">Post</button>
</form>
</script>
</body>
</html>
app.js:
var count = 0;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
count++;
return Math.floor(Math.random() * (max - min)) + min;
}
(function (){
angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}
])
.factory('posts', [function(){
// service body
var obj = {
posts: []
};
return obj;
}])
.controller('MainCtrl',[
'$scope',
'posts',
function($scope, posts){
$scope.test = 'Reddit Emulator';
$scope.posts = posts.posts
$scope.addPost = function(){
if ($scope.title === '' || $scope.title == null)
$scope.title = 'post ' + (count + 1);
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: getRandomInt(0,25)
});
$scope.posts = posts.posts
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
$scope.decrementUpvotes = function(post) {
post.upvotes -= 1;
};
}]);
})
THanks!
Top of my files seem to have gotten cut off but I don't have time to fix it ATM. Sorry
Your Javascript code encapsulated between
(function (){
...
})
needs to be executed in order to load the code inside. For that, You can add (); at the end
(function (){
...
})();
Your app.js is malformed.
Try this
angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}
])
.factory('posts', [function(){
// service body
var obj = {
posts: []
};
return obj;
}])
.controller('MainCtrl',[
'$scope',
'posts',
function($scope, posts){
$scope.test = 'Reddit Emulator';
$scope.posts = posts.posts
$scope.addPost = function(){
if ($scope.title === '' || $scope.title == null)
$scope.title = 'post ' + (count + 1);
$scope.posts.push({
title: $scope.title,
link: $scope.link,
upvotes: getRandomInt(0,25)
});
$scope.posts = posts.posts
$scope.title = '';
$scope.link = '';
};
$scope.incrementUpvotes = function(post) {
post.upvotes += 1;
};
$scope.decrementUpvotes = function(post) {
post.upvotes -= 1;
};
}]);
Then put the getRandomInt function inside the controller.

Make two layouts share the same $scope

I want to propose two layouts (ie, horizontal and vertical) for my contents. So switching in the selector will lead automatically to the corresponding layout. Here is the JSBin:
<html ng-app="flapperNews">
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>
<script type="text/ng-template" id="horizontal.tpl">
<textarea ng-model="one"></textarea>, <textarea ng-model="two"></textarea>
<br><br>{{one}}+{{two}}
</script>
<script type="text/ng-template" id="vertical.tpl">
<textarea ng-model="one"></textarea><br><textarea ng-model="two"></textarea>
<br><br>{{one}}+{{two}}
</script>
<script>
var app = angular.module('flapperNews', ['ui.router']);
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('entry', {
url: '/',
params: { tpl: 'vertical' },
templateUrl: function (params) {
return params.tpl + ".tpl"
}
})
}]);
app.controller('MainCtrl', ['$scope', '$state', function ($scope, $state) {
$scope.one = "one";
$scope.two = "two";
$scope.layouts = ["horizontal", "vertical"];
$scope.$watch('layout', function () {
$state.go('entry', {tpl: $scope.layout});
})
}])
</script>
</head>
<body ng-controller="MainCtrl">
<select ng-model="layout" ng-init="layout = 'horizontal' || layouts[0].value" ng-options="x for x in layouts"></select>
<br><br>
<ui-view></ui-view>
</body>
</html>
However, with the above code, each time we change the view, $scope.one and $scope.two are reset to their initial values. I would hope the change in their textarea would remain regardless of the change of layout.
Does anyone know how to solve this?
Easy sharing same data between different views by using factories (AngularJS factory documentation). Try this example, it uses a simple factory named myFactory to share data between controllers. This also does work on the same controller as in your case.
var myApp = angular.module("myApp",[ "ui.router"]);
myApp.config(function ($stateProvider, $urlRouterProvider){
$stateProvider.state("state1", {
url: "#",
template: '<p>{{ aValue }}</p><button ng-click="bindValue(\'its me\')">Bind value</button>',
controller: "myController"
}).state("state2", {
url: "#",
template: '<p>{{ aValue }}</p><button ng-click="bindValue(\'its me\')">Bind value</button>',
controller: "myController"
});
});
myApp.controller( "myController", function($scope, myFactory) {
$scope.aValue = myFactory.myValue;
$scope.bindValue = function (value) {
$scope.aValue = value;
myFactory.myValue = value;
}
});
myApp.factory('myFactory', function () {
return {
myValue: ''
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<div ng-app="myApp">
<nav>
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</nav>
<div ui-view></div>
</div>
I think that you should use nested views - you can define main controller on parent route state and define two nested states corresponding to two views. This way parent controller will remain (it's not re-initialised when child states are switched) and only nested states views will be changed. Something like this:
$stateProvider
.state('myState', {
url: '/test/',
template: '<div ui-view></div>',
controller: function() {
//main controller shared by child states
...
}
})
.state('myState.view1', {
url: '/test/view1'
templateUrl: 'tpl-1.hmtl',
...
})
.state('myState.view2', {
url: '/test/view2'
templateUrl: 'tpl-2.hmtl',
...
})

How to properly route with angular

I'm pretty new to angular and i'm trying to make a simple application, that switches few views with ng-view and ng-route.
for some reason, every link that i click always routes me to the same controller (HomeController).
This is my config
(function(){
'use strict';
angular
.module('app',['ngRoute'])
.config(myConfig);
myConfig.$inject = ['$routeProvider'];
function myConfig($routeProvider){
//noinspection JSUnresolvedFunction
$routeProvider
.when('/',{
templateUrl : 'templates/home.html',
controller : 'HomeController',
controllerAs : 'vm'
})
.when('/shop', {
templateUrl : 'templates/shop.html',
controller : 'ShopController',
controllerAs : 'vm'
})
.when('/cart', {
templateUrl : 'templates/cart.html',
controller : 'CartController',
controllerAs : 'vm'
})
.otherwise({
redirectTo: '/'
});
}
})();
This is my HTML:
<body ng-app="app">
<div id="site-wrapper">
<nav>
<ul>
<li class="button">Home</li>
<li class="button">Shop</li>
<li class="cart"><i class="fa fa-shopping-cart" aria-hidden="true"></i></li>
</ul>
</nav>
<ng-view></ng-view>
</div>
<script src="js/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-route.min.js"></script>
<script src="js/index.js"></script>
<script src="controllers/CartController.js"></script>
<script src="controllers/HomeController.js"></script>
<script src="controllers/ShopController.js"></script>
</body>
And here are 2 controllers for example:
(function(){
'use strict';
angular
.module('app')
.controller('CartController', CartController);
CartController.$inject = ['$scope', '$log'];
function CartController($scope, $log){
var vm = this;
$log.info('Cart CTRL loaded');
}
})();
(function(){
'use strict';
angular
.module('app')
.controller('HomeController', HomeController);
HomeController.$inject = ['$scope', '$log'];
function HomeController($scope , $log){
var vm = this;
$log.info('Home CTRL loaded');
}
})();
Off of a quick view, it seems to me that you need to remove the '#' in the href urls. So doing this may work better for you.
<nav>
<ul>
<li class="button">Home</li>
<li class="button">Shop</li>
<li class="cart"><i class="fa fa-shopping-cart" aria-hidden="true"></i></li>
</ul>
</nav>

Angular.js - Routing not working properly

I was making a simple routing program but it is not working properly. Following is my code:
index.html
<div class="container">
Create Event
<div ng-view></div>
</div>
NewEvent.html
<div>
<h1>{{event.name}}</h1>
</div>
EditEventController.js
eventsApp.controller('EditEventController',
function EditEventController($scope){
$scope.event = {name: 'Ayushi'}
});
app.js
var eventsApp = angular.module('eventsApp', ['ngRoute', 'ngResource']);
eventsApp.config(function($routeProvider) {
$routeProvider.when('/newEvent', {
templateUrl: 'templates/NewEvent.html',
controller: 'EditEventController'
})
.otherwise({redirectTo : '/'});
});

Controller called twice when used with angular material tabs

My controller gets called twice when I am using angular material tabs.
The tabs:
<div layout="column" flex="">
<md-content id="content">
<md-tabs md-dynamic-height="" md-selected="selectedIndex" md-border-bottom="" md-autoselect="">
<md-tab label="Home" ui-sref="home">
<div ui-view=""></div>
</md-tab>
<md-tab label="Contact" ui-sref="contact">
<div ui-view=""></div>
</md-tab>
</md-tabs>
</md-content>
</div>
The controllers:
(function () {
'use strict';
angular
.module('app.contact')
.controller('ContactController', ContactController);
function ContactController() {
var vm = this;
activate();
function activate() {
console.log('Contact Controller');
}
}
})();
(function () {
'use strict';
angular
.module('app.home')
.controller('HomeController', HomeController);
function HomeController() {
var vm = this;
activate();
function activate() {
console.log('Home Controller');
}
}
})();
The states:
(function () {
'use strict';
angular.module('app', [
])
.config(configBlock);
function configBlock($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$stateProvider
.state('home', {
url: "/home",
templateUrl: "home.html",
controller: 'HomeController',
controllerAs: 'vm'
})
.state('contact', {
url: "/contact",
templateUrl: "contact.html",
controller: 'ContactController',
controllerAs: 'vm'
});
}
})();
Plunker
This is, because you are using ui-view two times.
i also hav the same issue
use the ng-include instead of the ng-view
<md-tab label="Issues" >
<ng-include src="'/app/src/project/task/task.tpl.html'"></ng-include>
<!-- <div ui-view></div> -->
</md-tab>

Resources