本文翻译自:How to set bootstrap navbar active class with Angular JS?
If I have a navbar in bootstrap with the items 如果我在引导程序中有一个带有项目的导航栏
Home | About | Contact
How do I set the active class for each menu item when they are active? 如何为每个菜单项激活时设置活动类? That is, how can I set class="active"
when the angular route is at 也就是说,当角度路径class="active"
时,我如何设置class="active"
-
#/
for home#/
为家 -
#/about
for the about page#/about
about about page -
#/contact
for the contact page#/contact
联系页面
#1楼
参考:https://stackoom.com/question/15yCw/如何使用Angular-JS设置bootstrap-navbar活动类
#2楼
First and foremost, this problem can be solved in a lot of ways. 首先,这个问题可以通过很多方式解决。 This way might not be the most elegant, but it cerntainly works. 这种方式可能不是最优雅的,但它确实有效。
Here is a simple solution you should be able to add to any project. 这是一个简单的解决方案,您应该可以添加到任何项目。 You can just add a "pageKey" or some other property when you configure your route that you can use to key off of. 您可以在配置可用于关闭的路由时添加“pageKey”或其他属性。 Additionally, you can implement a listener on the $routeChangeSuccess method of the $route object to listen for the successful completion of a route change. 此外,您可以在$ route对象的$ routeChangeSuccess方法上实现一个侦听器,以侦听路由更改的成功完成。
When your handler fires you get the page key, and use that key to locate elements that need to be "ACTIVE" for this page, and you apply the ACTIVE class. 当您的处理程序触发时,您获取页面键,并使用该键来查找此页面需要“ACTIVE”的元素,并应用ACTIVE类。
Keep in mind you need a way to make ALL the elements "IN ACTIVE". 请记住,您需要一种方法使所有元素“处于活动状态”。 As you can see i'm using the .pageKey class on my nav items to turn them all off, and I'm using the .pageKey_{PAGEKEY} to individually turn them on. 正如你所看到我在我的导航项目上使用.pageKey类将它们全部关闭,我正在使用.pageKey_ {PAGEKEY}来单独打开它们。 Switching them all to inactive, would be considered a naive approach, potentially you'd get better performance by using the previous route to make only active items inactive, or you could alter the jquery selector to only select active items to be made inactive. 将它们全部切换为非活动状态将被视为一种天真的方法,可能通过使用先前的路由仅使活动项处于非活动状态来获得更好的性能,或者您可以将jquery选择器更改为仅选择要使其处于非活动状态的活动项。 Using jquery to select all active items is probably the best solution because it ensures everything is cleaned up for the current route in case of any css bugs that might have been present on the previous route. 使用jquery选择所有活动项可能是最好的解决方案,因为它可以确保在前一个路径上可能存在任何css错误的情况下清除当前路由的所有内容。
Which would mean changing this line of code: 这意味着改变这行代码:
$(".pagekey").toggleClass("active", false);
to this one 对这一个
$(".active").toggleClass("active", false);
Here is some sample code: 以下是一些示例代码:
Given a bootstrap navbar of 给出一个bootstrap导航栏
<div class="navbar navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="#">Title</a>
<ul class="nav">
<li><a href="#!/" class="pagekey pagekey_HOME">Home</a></li>
<li><a href="#!/page1/create" class="pagekey pagekey_CREATE">Page 1 Create</a></li>
<li><a href="#!/page1/edit/1" class="pagekey pagekey_EDIT">Page 1 Edit</a></li>
<li><a href="#!/page1/published/1" class="pagekey pagekey_PUBLISH">Page 1 Published</a></li>
</ul>
</div>
</div>
And an angular module and controller like the following: 和角度模块和控制器如下:
<script type="text/javascript">
function Ctrl($scope, $http, $routeParams, $location, $route) {
}
angular.module('BookingFormBuilder', []).
config(function ($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
template: 'I\'m on the home page',
controller: Ctrl,
pageKey: 'HOME' }).
when('/page1/create', {
template: 'I\'m on page 1 create',
controller: Ctrl,
pageKey: 'CREATE' }).
when('/page1/edit/:id', {
template: 'I\'m on page 1 edit {id}',
controller: Ctrl, pageKey: 'EDIT' }).
when('/page1/published/:id', {
template: 'I\'m on page 1 publish {id}',
controller: Ctrl, pageKey: 'PUBLISH' }).
otherwise({ redirectTo: '/' });
$locationProvider.hashPrefix("!");
}).run(function ($rootScope, $http, $route) {
$rootScope.$on("$routeChangeSuccess",
function (angularEvent,
currentRoute,
previousRoute) {
var pageKey = currentRoute.pageKey;
$(".pagekey").toggleClass("active", false);
$(".pagekey_" + pageKey).toggleClass("active", true);
});
});
</script>
#3楼
You can have a look at AngularStrap , the navbar directive seems to be what you are looking for: 您可以查看AngularStrap ,navbar指令似乎是您正在寻找的:
https://github.com/mgcrea/angular-strap/blob/master/src/navbar/navbar.js https://github.com/mgcrea/angular-strap/blob/master/src/navbar/navbar.js
.directive('bsNavbar', function($location) {
'use strict';
return {
restrict: 'A',
link: function postLink(scope, element, attrs, controller) {
// Watch for the $location
scope.$watch(function() {
return $location.path();
}, function(newValue, oldValue) {
$('li[data-match-route]', element).each(function(k, li) {
var $li = angular.element(li),
// data('match-rout') does not work with dynamic attributes
pattern = $li.attr('data-match-route'),
regexp = new RegExp('^' + pattern + '$', ['i']);
if(regexp.test(newValue)) {
$li.addClass('active');
} else {
$li.removeClass('active');
}
});
});
}
};
});
To use this directive: 要使用此指令:
Download AngularStrap from http://mgcrea.github.io/angular-strap/ 从http://mgcrea.github.io/angular-strap/下载AngularStrap
Include the script on your page after bootstrap.js: 在bootstrap.js之后在您的页面上包含脚本:
<script src="lib/angular-strap.js"></script>
Add the directives to your module: 将指令添加到您的模块:
angular.module('myApp', ['$strap.directives'])
Add the directive to your navbar: 将指令添加到导航栏:
<div class="navbar" bs-navbar>
Add regexes on each nav item: 在每个导航项上添加正则表达式:
<li data-match-route="/about"><a href="#/about">About</a></li>
#4楼
You can achieve this with a conditional in an angular expression, such as: 您可以使用角度表达式中的条件来实现此目的,例如:
<a href="#" class="{{ condition ? 'active' : '' }}">link</a>
That being said, I do find an angular directive to be the more "proper" way of doing it, even though outsourcing a lot of this mini-logic can somewhat pollute your code base. 话虽这么说,我确实发现一个角度指令是更“正确”的做法,即使外包很多这种迷你逻辑可能会在一定程度上污染你的代码库。
I use conditionals for GUI styling every once in a while during development, because it's a little quicker than creating directives. 我在开发期间偶尔使用条件进行GUI样式,因为它比创建指令快一点。 I couldn't tell you an instance though in which they actually remained in the code base for long. 我无法告诉你一个实例,虽然它们实际上长期存在于代码库中。 In the end I either turn it into a directive or find a better way to solve the problem. 最后,我要么把它变成一个指令,要么找到一个更好的方法来解决问题。
#5楼
I use ng-class directive with $location to achieve it. 我使用带有$ location的ng-class指令来实现它。
<ul class="nav">
<li data-ng-class="{active: ($location.path() == '/') }">
<a href="#/">Carpeta Amarilla</a>
</li>
<li class="dropdown" data-ng-class="{active: ($location.path() == '/auditoria' || $location.path() == '/auditoria/todos') }">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
Auditoria
<b class="caret"></b>
</a>
<ul class="dropdown-menu pull-right">
<li data-ng-class="{active: ($location.path() == '/auditoria') }">
<a href="#/auditoria">Por Legajo</a>
</li>
<li data-ng-class="{active: ($location.path() == '/auditoria/todos') }">
<a href="#/auditoria/todos">General</a>
</li>
</ul>
</li>
</ul>
It requires the navbar to be inside a main Controller with access to $location service like this: 它要求导航栏位于主控制器内,可以访问$ location服务,如下所示:
bajasApp.controller('MenuCntl', ['$scope','$route', '$routeParams', '$location',
function MenuCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}]);
#6楼
Here's a simple approach that works well with Angular. 这是一个适用于Angular的简单方法。
<ul class="nav navbar-nav">
<li ng-class="{ active: isActive('/View1') }"><a href="#/View1">View 1</a></li>
<li ng-class="{ active: isActive('/View2') }"><a href="#/View2">View 2</a></li>
<li ng-class="{ active: isActive('/View3') }"><a href="#/View3">View 3</a></li>
</ul>
Within your AngularJS controller: 在AngularJS控制器中:
$scope.isActive = function (viewLocation) {
var active = (viewLocation === $location.path());
return active;
};