AngularJS在为当前页面的链接设置一个活动类方面有任何帮助吗?
我想一定有什么神奇的方法可以做到,但我似乎找不到。
我的菜单是这样的:
<ul>
<li><a class="active" href="/tasks">Tasks</a>
<li><a href="/actions">Tasks</a>
</ul>
我在我的路由中为它们每个都有控制器:TasksController和ActionsController。
但是我想不出一种方法将a链接上的“活动”类绑定到控制器。
有提示吗?
我建议在链接上使用指令。
但它还不完美。小心哈希邦;)
下面是指令的javascript代码:
angular.module('link', []).
directive('activeLink', ['$location', function (location) {
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
var clazz = attrs.activeLink;
var path = attrs.href;
path = path.substring(1); //hack because path does not return including hashbang
scope.location = location;
scope.$watch('location.path()', function (newPath) {
if (path === newPath) {
element.addClass(clazz);
} else {
element.removeClass(clazz);
}
});
}
};
}]);
下面是它在html中的用法:
<div ng-app="link">
<a href="#/one" active-link="active">One</a>
<a href="#/two" active-link="active">One</a>
<a href="#" active-link="active">home</a>
</div>
之后用css样式:
.active { color: red; }
我找到了最简单的解决办法。只是比较HTML中的indexOf
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
$rootScope.isCurrentPath = $location.path();
});
});
<li class="{{isCurrentPath.indexOf('help')>-1 ? 'active' : '' }}">
<a href="/#/help/">
Help
</a>
</li>