如何使用Angular JS设置Bootstrap导航栏的活动类?
如何使用Angular JS设置Bootstrap导航栏的活动类?
如果我在bootstrap中有一个含有以下项的导航栏:
Home | About | Contact
当它们处于活动状态时,如何为每个菜单项设置活动类?也就是说,当angular路由位于以下情况时,如何设置class=\"active\"
:
- 主页使用
#/
- 关于页面使用
#/about
- 联系页面使用
#/contact
admin 更改状态以发布 2023年5月23日
我刚刚写了一个指令来处理这个问题,你只需要在父级
- 元素中添加属性
bs-active-link
,每当路由改变时,它将查找匹配的链接,并将active
类添加到相应的
中。
你可以在这里看到它的运作方式:http://jsfiddle.net/8mcedv3b/
示例 HTML:
Javascript:
angular.module('appName') .directive('bsActiveLink', ['$location', function ($location) { return { restrict: 'A', //use as attribute replace: false, link: function (scope, elem) { //after the route has changed scope.$on("$routeChangeSuccess", function () { var hrefs = ['/#' + $location.path(), '#' + $location.path(), //html5: false $location.path()]; //html5: true angular.forEach(elem.find('a'), function (a) { a = angular.element(a); if (-1 !== hrefs.indexOf(a.attr('href'))) { a.parent().addClass('active'); } else { a.parent().removeClass('active'); }; }); }); } } }]);