我正在使用 angularJS 和 bootstrap 来设计我的应用程序的导航。我定义了一个主 Controller ,在主 Controller 内我使用 ng-view 属性调用不同的页面 View ,然后这些单独的 View 有自己的 Controller 。
我正在使用 ng-class 属性将事件类添加到我的链接中,但是它不起作用。表达式的计算结果为 true 或 false,但 ng-class 不会更新元素上的 class="active"。
在我的主页上有以下代码 -
<section ng-controller="dashBoardCtrl" class="container">
<section class="row">
<h1>DME DashBoard | <small>WFM HeadCount</small> </h1>
</section>
<section class="row">
<ul class="nav nav-tabs">
<li role="presentation" ng-class="{active: {{path=='/'}}}"><a ng-href="#/">Home</a></li>
<li role="presentation" ng-class="{active: {{path=='/login'}}}"><a ng-href="#/login">Login</a></li>
</ul>
</section>
<section ng-view></section>
</section>
这就是在应用程序上配置路由的方式 -
dmeDash.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/views/home.html',
controller: 'homePageCtrl'
})
.when('/login', {
templateUrl: '/views/login.html',
controller: 'loginCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
dashBoardCtrl 有以下代码 -
dmeDashControllers.controller('dashBoardCtrl', ['$scope','$location', function($scope, $location) {
$scope.path = $location.$$path;
$scope.$watch('path',function(n,o) {
})
}]);
主页 Controller 具有以下代码 -
dmeDashControllers.controller('homePageCtrl', ['$scope','$location', function($scope, $location) {
$scope.$parent.path = $location.$$path;
}]);
登录页面 Controller 有以下代码 -
dmeDashControllers.controller('loginCtrl', ['$scope','$location', function($scope, $location) {
$scope.$parent.path = $location.$$path;
}]);
当我从主页单击到登录页面时,事件类不会从主页链接中删除,也不会应用于登录页面,但是,当我在 firebug 中查看代码时,表达式的计算结果为 true 或 false页面更改。
当我在各个页面上刷新时,ng-class 可以正常工作,但在使用超链接时则不能正常工作,请提出建议。
最佳答案
模板上的语法错误。应该是:
<li role="presentation" ng-class="{'active': path==='/'}"><a ng-href="#/">Home</a></li>
作为风格指南,尝试使用 ===
而不是简单的 ==
因为 type coercion 。或者测试真值或假值
关于javascript - ngClass 不更新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30622998/