AngularJS在为当前页面的链接设置一个活动类方面有任何帮助吗?
我想一定有什么神奇的方法可以做到,但我似乎找不到。
我的菜单是这样的:
<ul>
<li><a class="active" href="/tasks">Tasks</a>
<li><a href="/actions">Tasks</a>
</ul>
我在我的路由中为它们每个都有控制器:TasksController和ActionsController。
但是我想不出一种方法将a链接上的“活动”类绑定到控制器。
有提示吗?
这是一个扩展的kfis指令,我做了允许不同级别的路径匹配。从本质上讲,我发现需要匹配URL路径到一定深度,因为精确匹配不允许嵌套和默认状态重定向。希望这能有所帮助。
.directive('selectedLink', ['$location', function(location) {
return {
restrict: 'A',
scope:{
selectedLink : '='
},
link: function(scope, element, attrs, controller) {
var level = scope.selectedLink;
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) {
var i=0;
p = path.split('/');
n = newPath.split('/');
for( i ; i < p.length; i++) {
if( p[i] == 'undefined' || n[i] == 'undefined' || (p[i] != n[i]) ) break;
}
if ( (i-1) >= level) {
element.addClass("selected");
}
else {
element.removeClass("selected");
}
});
}
};
}]);
下面是我如何使用这个链接
<nav>
<a href="#/info/project/list" selected-link="2">Project</a>
<a href="#/info/company/list" selected-link="2">Company</a>
<a href="#/info/person/list" selected-link="2">Person</a>
</nav>
该指令将匹配在该指令的属性值中指定的深度级别。只是意味着它可以在其他地方多次使用。
我对这个问题的解决方案是使用路由。角模板中的电流。
当你在菜单中突出显示/tasks路由时,你可以将自己的属性menuItem添加到模块声明的路由中:
$routeProvider.
when('/tasks', {
menuItem: 'TASKS',
templateUrl: 'my-templates/tasks.html',
controller: 'TasksController'
);
然后在模板任务中。你可以使用以下ng-class指令:
<a href="app.html#/tasks"
ng-class="{active : route.current.menuItem === 'TASKS'}">Tasks</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; }