Reputation: 26192
Angular beginner here. I'm trying to basically have my link be active once I'm on a given page. Found quite couple of examples none of which work, so it must be that I'm doing wrong.
This is what I've been trying (controller) :
angular.module('MyApp')
.controller('HomeCtrl', ['$scope', function ($scope) {
$('body').addClass('homepage');
$scope.isActive = function(route) {
return route === $location.path();
}
}]);
Html :
<li "ng-class" = "{active:isActive('/') || isActive('/home')}">
Home
</li>
<li "ng-class" = "{active:isActive('/about')}">
About
</li>
<li "ng-class" = "{active:isActive('/contact')}">
Contact
</li>
Application itself :
var app = angular
.module('MyApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'templates',
'ng-token-auth'
]).config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
})
.when('/', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
})
.when('/contact', {
templateUrl: 'contact.html',
controller: 'ContactCtrl'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}])
So no matter on which page I'm located at, the ng-class
does nothing with no errors in the console. However if I do this for home:
<li "ng-class" = "{active:true}">
Home
</li>
Then I get active class on my link, and this is the output :
<li ng-class="{active:true}" class="active">
Home
</li>
What am I doing wrong here? Why doesn't it interpolate the function isActive as it should?
Upvotes: 0
Views: 86
Reputation: 42669
You cannot have the logic to check the active link inside your HomeCtrl
as it is one of the routes. When other routes are loaded there is no HomeCtrl
loaded.
There should be controller defined outside the ng-view, such as RootCtrl
. The isActive
function should be added to it.
Since the child view scope would have access to parent scope, you can use the isActive
in the child views normally.
Update: Consider the html
<body ng-controller='RootCtrl'>
<div ng-view></div>
</body>
Add the isActive function on the RootCtrl
.
Upvotes: 1