如果我有一个导航栏在引导项目
Home | About | Contact
当每个菜单项处于活动状态时,如何为它们设置活动类?也就是说,当角路由为at时,我如何设置class="active"
#/ home #/about用于about页面 #/contact为联系人页面
如果我有一个导航栏在引导项目
Home | About | Contact
当每个菜单项处于活动状态时,如何为它们设置活动类?也就是说,当角路由为at时,我如何设置class="active"
#/ home #/about用于about页面 #/contact为联系人页面
当前回答
以下是我的看法。在这篇文章中找到了一些答案的组合。我有一个稍微不同的情况下,所以我的解决方案涉及到分离菜单到自己的模板,在指令定义Ojbect中使用,然后添加我的导航栏到我需要它的页面。基本上,我有一个登录页面,我不想包括我的菜单,所以我使用ngInclude并在登录时插入这个指令:
指令:
module.directive('compModal', function(){
return {
restrict: 'E',
replace: true,
transclude: true,
scope: true,
templateUrl: 'templates/menu.html',
controller: function($scope, $element, $location){
$scope.isActive = function(viewLocation){
var active = false;
if(viewLocation === $location.path()){
active = true;
}
return active;
}
}
}
});
指令模板(templates/menu.html)
<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>
包含指令的HTML
<comp-navbar/>
希望这能有所帮助
其他回答
JavaScript
/**
* Main AngularJS Web Application
*/
var app = angular.module('yourWebApp', [
'ngRoute'
]);
/**
* Setup Main Menu
*/
app.controller('MainNavCtrl', [ '$scope', '$location', function ( $scope, $location) {
$scope.menuItems = [
{
name: 'Home',
url: '/home',
title: 'Welcome to our Website'
},
{
name: 'ABOUT',
url: '/about',
title: 'Know about our work culture'
},
{
name: 'CONTACT',
url: '/contact',
title: 'Get in touch with us'
}
];
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
}]);
HTML
<div class="navbar-collapse collapse" ng-controller="MainNavCtrl">
<ul id="add-magic-line" class="nav navbar-nav navbar-right">
<li data-ng-class="{current_page_item: isActive('{{ menuItem.url }}')}" data-ng-repeat="menuItem in menuItems">
<a data-ng-href="#{{menuItem.url}}" title="{{menuItem.title}}">
{{menuItem.name}}
</a>
</li>
</ul>
</div>
只是为了补充我的观点,我做了一个纯angular模块(没有jquery),它也可以用于包含数据的散列url。(专营# /这个/ /路径?这=一些=数据)
您只需将模块作为依赖项添加并自动激活到菜单的一个祖先。是这样的:
<ul auto-active>
<li><a href="#/">main</a></li>
<li><a href="#/first">first</a></li>
<li><a href="#/second">second</a></li>
<li><a href="#/third">third</a></li>
</ul>
这个模块是这样的:
(function () {
angular.module('autoActive', [])
.directive('autoActive', ['$location', function ($location) {
return {
restrict: 'A',
scope: false,
link: function (scope, element) {
function setActive() {
var path = $location.path();
if (path) {
angular.forEach(element.find('li'), function (li) {
var anchor = li.querySelector('a');
if (anchor.href.match('#' + path + '(?=\\?|$)')) {
angular.element(li).addClass('active');
} else {
angular.element(li).removeClass('active');
}
});
}
}
setActive();
scope.$on('$locationChangeSuccess', setActive);
}
}
}]);
}());
*(当然你可以只使用指令部分)
**值得注意的是,这并不适用于空哈希值(i.g. example.com/#或仅example.com),它至少需要example.com/#/或仅example.com#/。但这是自动发生的ngResource之类的。
这是小提琴:http://jsfiddle.net/gy2an/8/ 这里是github: https://github.com/Karl-Gustav/autoActive 这是我最初的答案:https://stackoverflow.com/a/22282124/1465640
首先,这个问题可以用很多方法来解决。这种方式可能不是最优雅的,但它确实有效。
这里有一个简单的解决方案,你应该能够添加到任何项目。当你配置你的路由时,你可以添加一个“pageKey”或其他属性,你可以用它来关闭。另外,你可以在$route对象的$routeChangeSuccess方法上实现一个监听器来监听路由更改是否成功完成。
当您的处理程序触发时,您将获得页面键,并使用该键来定位需要为该页“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. 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. 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.
这意味着要修改这行代码:
$(".pagekey").toggleClass("active", false);
到这个
$(".active").toggleClass("active", false);
下面是一些示例代码:
给出一个引导导航条
<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>
以及一个角模块和控制器,如下所示:
<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>
你可以看看AngularStrap,它的导航条指令似乎就是你要找的:
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');
}
});
});
}
};
});
使用这个指令:
从http://mgcrea.github.io/angular-strap/下载AngularStrap 包括脚本在你的页面bootstrap.js之后: < script src = " lib / angular-strap.js " > < /脚本> 添加指令到你的模块: 角。模块(“myApp”,[' strap.directives美元']) 添加指令到你的导航栏: <div class="navbar" b -navbar> 在每个导航项上添加正则表达式: <李data-match-route = " / " > < a href = " # /约" >对< / > < /李>
一个非常优雅的方法是使用ng-controller在ng-view之外运行一个单独的控制器:
<div class="collapse navbar-collapse" ng-controller="HeaderController">
<ul class="nav navbar-nav">
<li ng-class="{ active: isActive('/')}"><a href="/">Home</a></li>
<li ng-class="{ active: isActive('/dogs')}"><a href="/dogs">Dogs</a></li>
<li ng-class="{ active: isActive('/cats')}"><a href="/cats">Cats</a></li>
</ul>
</div>
<div ng-view></div>
并包含在controllers.js中:
function HeaderController($scope, $location)
{
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
}