我有一个基于以下示例的菜单:
<nav data-ng-controller="menuContrl" class="menuItem"> <a data-ng-class='{active:isActive("/{{item.path}}")}' data-ng-repeat="item in menu" href="#/{{item.path}}"> <span>{{item.title}}</span> </a> </nav>
item是一个对象,包含菜单项信息。这是指令和控制器的JavaScript代码:
var app = angular.module("coolApp",[]); function menuContrl($scope,$location){ $scope.menu=menu; $scope.isActive = function(path){ return ($location.path()==path) } }
问题是,ng- class套class到active只有一次页面渲染过程中,但是当你点击一个菜单项,没有一切发生的时候。我想这是因为菜单本身并未重新加载,而我只是在其中更改了数据<div>。那么如何在不重新加载整个页面的情况下使它工作呢?
ng- class
class
active
<div>
//jsfiddle.net/uDPHL/146/
的旧版本中存在此问题angular js [Reference](https://github.com/angular/angular.js/issues/4002),将其升级到angular js 1.2.0版本后已解决。
angular js
[Reference](https://github.com/angular/angular.js/issues/4002)
angular js 1.2.0
JS:-
var navList = angular.module('navList', []); navList.controller('navCtrl', ['$scope', '$location', function ($scope, $location) { $scope.navLinks = [{ Title: 'home', LinkText: 'Home', }, { Title: 'about', LinkText: 'About Us' }, { Title: 'contact', LinkText: 'Contact Us' }]; $scope.navClass = function (page) { var currentRoute = $location.path().substring(1) || 'home'; return page === currentRoute ? 'active' : ''; }; }]);
HTML:-
<div class="well sidebar-nav" ng-app="navList"> <ul class="nav nav-list" ng-controller="navCtrl"> <li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title}}')"> <a href='#/{{navLink.Title}}'>{{navLink.LinkText}}</a> </li> </ul> </div>