Angularjs routing issue controller not triggered after click the link ? - angularjs

I have implemented the routing in our website i have properly link all the href with controller but i don't understand why controller is not fire check my fiddle code and tell what's the wrong in my code?
var app = angular.module("angularDemoApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when('/Family', {
templateURL : 'Family.html',
controller : 'familyController'
}).when('/Friends',{
templateURL : 'Friends.html',
controller : 'friendsController'
}).when('/Photo', {
templateURL : 'Photo.html',
controller : 'photoController'
})
})
app.controller('familyController', function($scope) {
$scope.msg = "hiii homeee";
});
app.controller('friendsController', function($scope) {
alert('ssss');
$scope.friendsMsg = "hiii friendsMsg";
});
app.controller('photoController', function($scope) {
alert('ssss');
$scope.photoMsg = "hiii photoMsg";
})
<ul class="nav nav-pills nav-stacked">
<li>
Family
</li>
<li>
Friends
</li>
<li>
Photos
</li>
</ul>

If you are using angular version above 1.6 routes changed from #/state to #!/state
DEMO
var app = angular.module("angularDemoApp", ["ngRoute"])
app.config(function($routeProvider) {
$routeProvider.when('/Family', {
template: `<h1>{{msg}}</h1>`,
controller : 'familyController'
}).when('/Friends',{
template: `<h1>{{friendsMsg}}</h1>`,
controller : 'friendsController'
}).when('/Photo', {
template: `<h1>{{photoMsg}}</h1>`,
controller : 'photoController'
})
})
app.controller('familyController', function($scope) {
$scope.msg = "hiii homeee";
});
app.controller('friendsController', function($scope) {
alert('ssss');
$scope.friendsMsg = "hiii friendsMsg";
});
app.controller('photoController', function($scope) {
alert('ssss');
$scope.photoMsg = "hiii photoMsg";
})
<!DOCTYPE html>
<html ng-app="angularDemoApp">
<head>
<meta charset="utf-8" />
<title>AngularJS User Registration and Login Example </title>
</head>
<body>
<ul class="nav nav-pills nav-stacked">
<li>
Family
</li>
<li>
Friends
</li>
<li>
Photos
</li>
</ul>
<div class="mainContainer" ng-view></div>
<script src="//unpkg.com/angular#1.6/angular.js"></script>
<script src="//unpkg.com/angular-route#1.6/angular-route.js"></script>
</body>
</html>

Related

AngularJS controller not properly loaded during ng-Route otherwise()

I'm learning an example of a single page application using angularjs. Here's the relevant code:
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"/>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<script>
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
// configure the routes
$routeProvider
.when('/', {
// route for the home page
templateUrl: 'pages/home.html',
controller: 'homeController'
})
.when('/about/', {
// route for the about page
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
.when('/contact/', {
// route for the contact page
templateUrl: 'pages/contact.html',
controller: 'contactController'
})
.otherwise({
// when all else fails
templateUrl: 'pages/routeNotFound.html',
controller: 'notFoundController'
});
});
app.controller('homeController', function ($scope) {
$scope.message = 'Welcome to my home page!';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'Find out more about me.';
});
app.controller('contactController', function ($scope) {
$scope.message = 'Contact us!';
});
app.controller('notFoundController', function ($scope) {
$scope.message = 'There seems to be a problem finding the page you wanted';
$scope.attemptedPath = $location.path();
});
</script>
</head>
<body ng-controller="homeController">
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">My Website</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact</li>
</ul>
</div>
</nav>
</header>
<div id="main">
<!-- this is where content will be injected -->
<div ng-view></div>
</div>
</body>
</html>
routeNotFound.html
<div class="jumbotron text-center">
<h1>This is not good</h1>
<p>{{message}}</p>
<p class="has-error">{{attemptedPath}}</p>
</div>
When I click on Home or About or Contact the page renders correctly. But if I visit any other URL, routeNotFound.html is injected correctly to div[ng-view] but the data is not bound. I get:
This is not good
{{message}}
{{attemptedPath}}
It seems notFoundController is not correctly made available to the view when .otherwise() is called inside route. $scope.message and $scope.attemptedPath is not bound to the view.
You are missing $locationService injection in your notFoundController
app.controller('notFoundController', function ($scope,$location /*<--- location injected here*/) {
$scope.message = 'There seems to be a problem finding the page you wanted';
$scope.attemptedPath = $location.path();
});
Here is a full sample:
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
// configure the routes
$routeProvider
.when('/', {
// route for the home page
template: '<h1>My page home</h1><br />{{message}}',
controller: 'homeController'
})
.when('/about/', {
// route for the about page
template: '<h1>My page about</h1><br />{{message}}',
controller: 'aboutController'
})
.when('/contact/', {
// route for the contact page
template: '<h1>My page contact</h1><br />{{message}}',
controller: 'contactController'
})
.otherwise({
// when all else fails
template: '<h1>Not found page</h1><br />{{message}}',
controller: 'notFoundController'
});
});
app.controller('homeController', function ($scope) {
$scope.message = 'Welcome to my home page!';
});
app.controller('aboutController', function ($scope) {
$scope.message = 'Find out more about me.';
});
app.controller('contactController', function ($scope) {
$scope.message = 'Contact us!';
});
app.controller('notFoundController', function ($scope,$location) {
$scope.message = 'There seems to be a problem finding the page you wanted';
$scope.attemptedPath = $location.path();
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"/>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<script>
</script>
</head>
<body ng-controller="homeController">
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">My Website</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact</li>
<li><i class="fa fa-comment"></i> Not found</li>
</ul>
</div>
</nav>
</header>
<div id="main">
<!-- this is where content will be injected -->
<div ng-view></div>
</div>
</body>
</html>

AngularJS routing: Views are not getting updated

I am learning how to implement routing in AngularJS. Everything else is working fine but the views are not getting updated when I click on the navigation.
How can I achieve the desired functionality in the application? I want the navigation to take us to the desired pages without refreshing the page and that's quite obvious.
Here is the code.
Index.html
<!DOCTYPE html>
<html ng-app="routingApp">
<head>
<title>AngularJS routing</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular-route.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="routingAppController">
<!-- Header and Navigation -->
<header>
<nav class= "navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Angular Routing App</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</nav>
</header>
<!-- Main Body where content will be injected -->
<div id="main">
<div ng-view></div>
</div>
</body>
</html>
Script.js
(function(){
'use strict';
var app = angular.module('routingApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'routingAppController'
})
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
app.controller('routingAppController', function($scope){
$scope.message = "This will get updated for sure!";
});
app.controller('aboutController', function($scope){
$scope.message = "This is the about page and it looks awesome!";
});
app.controller('contactController', function($scope){
$scope.message = "This is the contact page!";
});
})();
One of the pages
<div class="jumbotron text-center">
<h1>Home Page</h1>
<p>{{ message }}</p>
</div>

Passing Data between state Providers in angular

Im looking to pass data between 2 controllers in Angular, Below is code i started
There are 2 views one with input field and other with a link.
when i click on link in the second view i should be able to set a state and state data should be populated in input field in first field.
I tried several approaches but im missing something.
Can someone help me here
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$stateProvider','$stateProvider', '$urlRouterProvider', function ($stateProvider,$urlRouterProvider) {
var addBook = {
name: 'addBook',
url: '/addBook',
template: '<h2>Add A book</h2> Data from View <input type="text" ng-model={{input-text}}>' ,
data:""
},
viewBookv = {
name: 'viewBookv',
url: '/viewBook',
template: '<h2>View A book</h2><span class="glyphicon glyphicon-edit">Edit</span> ' ,
};
$stateProvider.state(addBook, "controller: editUserCtrl");
$stateProvider.state(viewBookv, "controller: editUserCtrl");
}])
myApp.controller('editUserCtrl', function($scope, $stateParams) {
$scope.paramOne = $stateParams.data;
$scope.edit = function () {
event.preventDefault();
$state.go("addBook");
}
})
myApp.controller('mainController',function($scope, $rootScope, $state,$window){
$scope.addBook=function(){
$state.go("addBook");
};
$scope.viewbookls= function(){
$state.go("viewBookv");
};
})
</script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3" ng-controller="mainController">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ui-view></div>
</div>
</div>
</div>
</body>
</html>
Typically in angular the way to share state between controllers is using a service. So the way it's usually set up is to setup a service then import that service into the relevant controllers, and that data gets shared between them. I've modified your example above to follow this pattern(I'm not quite sure what you were trying to do)
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider,$urlRouterProvider) {
var addBook = {
name: 'addBook',
url: '/addBook',
template: '<h2>Add A book</h2> Data from View <button ng-click="updateBook()">Update</button> <input type="text" ng-model="inputText">' ,
controller: "addBookCtrl",
data:""
},
viewBookv = {
name: 'viewBooks',
url: '/viewBook',
template: '<h2>View A book</h2><div ng-repeat="book in bookList">{{book}}</div>',
controller: "viewBookCtrl",
};
$stateProvider.state('addBook', addBook);
$stateProvider.state('viewBooks', viewBookv);
}])
myApp.controller('addBookCtrl', function($scope, bookService) {
$scope.updateBook = function(){
console.log( $scope.inputText)
bookService.books.push($scope.inputText);
}
})
myApp.controller('viewBookCtrl', function($scope, bookService) {
$scope.bookList = bookService.books
})
myApp.factory('bookService', function() {
var bookService = {};
bookService.books = [];
return bookService;
});
myApp.controller('mainController',function($scope, $rootScope, $state,$window){
$scope.addBook=function(){
$state.go("addBook");
};
$scope.viewbookls= function(){
$state.go("viewBooks");
};
})
</script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3" ng-controller="mainController">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ui-view></div>
</div>
</div>
</div>
</body>
</html>
What this example does, is in the text box for add book, you type in the name (then click update), this appends it to an array so every time you do it you'll get a new element on that array. From there head over to the view books page, and you'll see all the different things you typed in.

How to get AngularJS routing to maintain state?

I'm getting up to speed with AngularJS routing and have created this example which works.
However, I understood that if on page "home" I type in a text into the input box, then click on page "about" and then come back to "home", the text would still be in the input box, i.e. would have maintained the state.
Is this not the case, and if not, is there a way to maintain state in forms on pages which the user navigates away from?
home.htm
<div class="jumbotron">
<h1>Home</h1>
<p>{{subtitle}}</p>
</div>
<input ng-model="message"/>
index.htm
<html ng-app="mainApp">
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" rel="stylesheet" />
<style type="text/css">
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
a:focus {
outline: none;
}
</style>
</head>
<body ng-cloak ng-controller="mainController">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<div class="navbar-brand">AngularJS Routing</div>
</div>
<div>
<ul class="nav navbar-nav">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact</li>
</ul>
</div>
</div>
</nav>
<div class="col-lg-12">
<div ng-view></div>
</div>
<script>
var mainApp = angular.module('mainApp', ['ngRoute']);
mainApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.htm',
controller: 'mainController'
})
.when('/about', {
templateUrl: 'pages/about.htm',
controller: 'aboutController'
})
.when('/contact', {
templateUrl: 'pages/contact.htm',
controller: 'contactController'
})
.otherwise({
redirectTo: '/'
});
});
mainApp.controller('mainController', function ($scope) {
$scope.subtitle = 'the home page';
$scope.message = '';
});
mainApp.controller('aboutController', function ($scope) {
$scope.subtitle = 'the about page';
});
mainApp.controller('contactController', function ($scope) {
$scope.subtitle = 'the contact page';
});
</script>
</body>
</html>
Controllers do not maintain state, they are created and destroyed every time you go through the route. You will need to implement a service that you can use to store your data and then have a means to send the data to the service when you want to persist it. Controller have a '$destroy' event that occurs right before the scope is released that you can hook.
mainApp.service('myData', function() {
this.message = '';
})
.controller('mainController', function($scope, myData) {
$scope.message = myData.message;
$scope.$on("$destroy", function() {
myData.message = $scope.message;
});
});

AngularJS orderby / controller behavior: controller executed on orderby

I took a sample AngularJS app and began to change it to suit my needs. Now clicking to change the orderby causes the entire controller to be reloaded. Well that's where I'm initializing the default orderby. So what I get when I click a new orderby is a flash of the proper orderby then a quick return to the default. An alert showed me the controller is getting executed but I don't know why or how to fix it.
Plunker here
index.html
<!DOCTYPE html>
<html data-ng-app="promptsApp">
<head>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="style.css" rel="stylesheet" />
</head>
<body>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="app.js"></script>
<script src="controllers.js"></script>
<script src="promptsService.js"></script>
</body>
</html>
app.js
var app = angular.module('promptsApp', []);
app.config(function ($routeProvider) {
$routeProvider
.when('/prompts',
{
controller: 'PromptsController',
templateUrl: 'partial.html'
})
.otherwise({ redirectTo: '/prompts' });
});
controllers.js
app.controller('PromptsController', function ($scope, promptsService)
{
init();
function init()
{
$scope.prompts = promptsService.getPrompts();
$scope.orderby='TRANSFEREE';
$scope.reverse = false;
//alert('Hi');
}
$scope.setOrder = function (orderby) {
if (orderby === $scope.orderby)
{
$scope.reverse = !$scope.reverse;
}
$scope.orderby = orderby;
};
});
promptsService.js
app.service('promptsService', function ()
{
this.getPrompts = function (user)
{
var prompts = [
{
id: 1, NOTE: 'Call client about something', CALLBACK_DATE: '12-01-2013', TRANSFEREE: 'Tom Tuttle', REG_NUM: '123456'
},
{
id: 2, NOTE: 'Notify client of delay', CALLBACK_DATE: '12-10-2013', TRANSFEREE: 'Eddie Munster', REG_NUM: '101314'
},
{
id: 3, NOTE: 'Complete paperwork', CALLBACK_DATE: '12-12-2013', TRANSFEREE: 'Mary Tyler Moore', REG_NUM: '998877'
}
];
return prompts;
};
});
partial.html
<div class="prompts">
<div class="container">
<header>
<h3>Prompts</h3>
<ul class="nav nav-pills">
<li ng-class="{'active': orderby=='CALLBACK_DATE'}">Date</li>
<li ng-class="{'active': orderby=='TRANSFEREE'}">Transferee</li>
<li> (Currently: {{orderby}})</li>
</ul>
</header>
<div>
<div class="row cardContainer">
<div class="span3 card" data-ng-repeat="prompt in prompts | orderBy:orderby:reverse">
<div class="cardHeader">{{prompt.TRANSFEREE}}</div>
<div class="cardBody">{{prompt.NOTE}}
<br># {{prompt.REG_NUM}} {{prompt.CALLBACK_DATE}}
</div>
</div>
</div>
</div>
<br />
{{prompts.length}} prompts
</div>
</div>
See Plunker here
<li ng-class="{'active': orderby=='CALLBACK_DATE'}">
<a href="" ng-click="setOrder('CALLBACK_DATE')">\
CallBack Date
</a>
</li>
<li ng-class="{'active': orderby=='TRANSFEREE'}">
<a href="" ng-click="setOrder('TRANSFEREE')">
Transferee
</a>
</li>
<li>> Currently: {{orderby}}</li>
Remove the href="#" and replace it with href="" to get the desired result.
Having href="#" causes the route to change (and become the same as before) but triggers the initialization of the controller once more.

Resources