I am pretty new to AngularJS so I'm doing an experiment. I want to change the active class of my navigation when I go to a new page. I want to make a specific controller variable for this, HeaderCtrl is the controller, defined in the app.js file:
'use strict';
/**
* @ngdoc overview
* @name ePortfolioApp
* @description
* # ePortfolioApp
*
* Main module of the application.
*/
var app = angular.module('ePortfolioApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/personality', {
templateUrl: 'views/personality.html',
controller: 'PersonalityCtrl'
})
.
when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactCrl'
})
.when('/projects' ,{
templateUrl: 'views/projects.html',
controller: 'ProjectsCtrl'
})
.otherwise({
redirectTo: '/'
});
});
$rootScope.$on('$routeChangeStart', function (evt, next, currentRoute) {
$rootScope.isActive = next.$$route.routeName;
}
}
app.controller('HeaderCtrl', ['$scope', function($scope){
$scope.isActive = 'main';
}])
$rootScope.$watch('isActive', function() {
$scope.isActive = $rootScope.isActive;
});
My HTML has following code:
<div class="collapse navbar-collapse" id="js-navbar-collapse">
<ul class="nav navbar-nav">
<li ng-class="isActive == 'main' ? 'active' : ' ' "><a href="#/">Home</a></li>
<li ng-class="isActive == 'about' ? 'active' : ' ' "><a ng-href="#/about">About</a></li>
<li ng-class="isActive == 'projects' ? 'active' : ' ' "><a ng-href="#/projects">Projects</a></li>
<li ng-class="isActive == 'personality' ? 'active' : ' ' "><a ng-href="#/personality">Personality</a></li>
<li ng-class="isActive == 'contact' ? 'active' : ' ' "><a ng-href="#/contact">Contact</a></li>
</ul>
</div>
What is wrong?
Basically
next.$$route
return array defined in$routeProvider
when condition. For making you code working you need to do addrouteName
parameter into your each route which will make your code working.Code
In addition you need to put
$routeChangeStart
in a run blockDemo Plunkr