我有一些html,我正在尝试使用ng-class。如果我只是硬编码为“true”,我的CSS类将按预期应用。但是,只要我用表达式替换true(如下所示),似乎我的类没有被应用。这是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>
来自控制器的代码:
$scope.$on('$routeChangeSuccess', function(index){
$scope.activeIndex = index;
console.log("Set Active Index");
});
答案 0 :(得分:1)
似乎'$ routeChangeSuccess'事件回调的索引参数不是您预期的数字。 如果要在路线更改时更改活动列表。您可以将$ location服务传递给$ scope。
这里是示例: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代码:
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');
});