Reputation: 507
I have some html with which I'm trying to use ng-class. If I just hardcode in "true", my CSS for the class is applied as expected. But, as soon as I replace the true with an expression (shown below), it seems my class isn't being applied. Here is the line of HTML:
<li ng-repeat="menuItem in menuItems"><span ng-class="{active: $index==activeIndex}" class="underline"><a ng-href={{menuItem.itemLink}}>{{menuItem.itemName}}</a></span></li>
And the code from the controller:
$scope.$on('$routeChangeSuccess', function(index){
$scope.activeIndex = index;
console.log("Set Active Index");
});
Upvotes: 0
Views: 824
Reputation: 588
It seems the index param of the '$routeChangeSuccess' event callback is not a number as you expected. If you want to change your actived list when route change. you can pass $location service to $scope.
here is example: http://jsfiddle.net/yRHwm/4/
HTML code:
<div ng-app="myapp">
<div class="container" ng-controller="MyCtrl">
<li ng-repeat="menuItem in menuItems">
<!-- use $location.path() to detect current path -->
<span ng-class="{'active': menuItem.itemLink==$location.path()}" class="underline">
<a ng-href="#{{menuItem.itemLink}}">{{menuItem.itemName}}</a>
</span>
</li>
</div>
<div ng-view></div>
</div>
Javscript Code:
angular.module('myapp', ['ngRoute'])
.config(function($routeProvider){
$routeProvider
.when('/1', {controller:'firstController'})
.when('/2', {controller:'secondController'})
})
.controller('MyCtrl', function($scope, $location) {
$scope.menuItems = [
{itemLink: '/1', itemName: 'Link1'},
{itemLink: '/2', itemName: 'Link2'}
];
// pass $location service to scope, then you can use $location.path() to detect current path
$scope.$location = $location;
// this is no longer used. just to show index is not a number
$scope.$on('$routeChangeSuccess', function(index){
$scope.activeIndex = index;
// you can see in the console which index is not a number.
console.log("Set Active Index", index);
});
})
.controller('firstController', function($scope){
console.log('first');
})
.controller('secondController', function($scope){
console.log('second');
});
Upvotes: 1