如何设置带角JS的引导导航条主动类?

时间:2022-11-03 20:07:44

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"

  1. #/ for home
  2. # /回家
  3. #/about for the about page
  4. #/关于about页面。
  5. #/contact for the contact page
  6. #/联系人页

25 个解决方案

#1


585  

A very elegant way is to use ng-controller to run a single controller outside of the ng-view:

一种非常优雅的方式是使用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>

and include in controllers.js:

在controllers.js,包括:

function HeaderController($scope, $location) 
{ 
    $scope.isActive = function (viewLocation) { 
        return viewLocation === $location.path();
    };
}

#2


50  

I just wrote a directive to handle this, so you can simply add the attribute bs-active-link to the parent <ul> element, and any time the route changed, it will find the matching link, and add the active class to the corresponding <li>.

我刚刚编写了一个指令来处理这个问题,所以您可以简单地将属性bs-active-link添加到父元素

    元素中,并且只要路由改变,它就会找到匹配的链接,并将活动类添加到相应的
  • 中。

  • 中。

You can see it in action here: http://jsfiddle.net/8mcedv3b/

您可以在这里看到它的作用:http://jsfiddle.net/8mcedv3b/

Example HTML:

示例HTML:

<ul class="nav navbar-nav" bs-active-link>
  <li><a href="/home">Home</a></li>
  <li><a href="/contact">Contact</a></li>
</ul>

Javascript:

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');   
                };
            });     
        });
    }
}
}]);

#3


38  

You can have a look at AngularStrap, the navbar directive seems to be what you are looking for:

你可以看看角带,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:

使用这个指令:

  1. Download AngularStrap from http://mgcrea.github.io/angular-strap/

    从http://mgcrea.github.io/angular-strap/下载AngularStrap

  2. Include the script on your page after bootstrap.js:
    <script src="lib/angular-strap.js"></script>

    在引导之后将脚本包含在页面上。js:< script src = " lib / angular-strap.js " > < /脚本>

  3. Add the directives to your module:
    angular.module('myApp', ['$strap.directives'])

    向模块添加指令:角度。模块(“myApp”,[' strap.directives美元'])

  4. Add the directive to your navbar:
    <div class="navbar" bs-navbar>

    向导航条中添加指令:

  5. Add regexes on each nav item:
    <li data-match-route="/about"><a href="#/about">About</a></li>

    在每个nav项目上增加regexes:

  6. about
  7. 关于

#4


32  

Here's a simple approach that works well with 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;
};

#5


8  

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. Additionally, you can implement a listener on the $routeChangeSuccess method of the $route object to listen for the successful completion of a route change.

这里有一个简单的解决方案,您应该能够添加到任何项目中。您可以在配置路由时添加“pageKey”或其他一些属性,您可以使用这些属性来进行键合。此外,您可以在$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.

当处理程序触发时,您将获得页面键,并使用该键定位需要为该页“活动”的元素,然后应用活动类。

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类将它们全部关闭,而我使用. pagekey_ {PAGEKEY}将它们单独打开。将它们全部切换为非活动的,将被认为是一种幼稚的方法,您可以使用前面的路由来使活动项处于非活动状态,从而获得更好的性能,或者您可以将jquery选择器更改为只选择不活动的活动项。使用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

给出一个引导导航条

<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>

#6


7  

You can actually use angular-ui-utils' ui-route directive:

你可以使用angular-ui-utils的ui-route指令:

<a ui-route ng-href="/">Home</a>
<a ui-route ng-href="/about">About</a>
<a ui-route ng-href="/contact">Contact</a>

or:

或者:

Header Controller

/**
 * Header controller
 */
angular.module('myApp')
  .controller('HeaderCtrl', function ($scope) {
    $scope.menuItems = [
      {
        name: 'Home',
        url:  '/',
        title: 'Go to homepage.'
      },
      {
        name:   'About',
        url:    '/about',
        title:  'Learn about the project.'
      },
      {
        name:   'Contact',
        url:    '/contact',
        title:  'Contact us.'
      }
    ];
  });

Index page

<!-- index.html: -->
<div class="header" ng-controller="HeaderCtrl">
  <ul class="nav navbar-nav navbar-right">
    <li ui-route="{{menuItem.url}}" ng-class="{active: $uiRoute}"
      ng-repeat="menuItem in menuItems">
      <a ng-href="#{{menuItem.url}}" title="{{menuItem.title}}">
        {{menuItem.name}}
      </a>
    </li>
  </ul>
</div>

If you're using ui-utils, you may also be interested in ui-router for managing partial/nested views.

如果您使用的是ui-utils,您可能也会对ui-router感兴趣,用于管理部分/嵌套视图。

#7


6  

I find all of these answers a bit over complicated for me, sorry. So I have created a small directive that should work on a per navbar basis:

我发现这些答案对我来说有点复杂,抱歉。所以我创建了一个小指令,应该在每个导航条的基础上工作:

app.directive('activeLink', function () {
    return {
        link: function (scope, element, attrs) {
            element.find('.nav a').on('click', function () {
                angular.element(this)
                    .parent().siblings('.active')
                    .removeClass('active');
                angular.element(this)
                    .parent()
                    .addClass('active');
            });
        }
    };
});

Usage:

用法:

<ul class="nav navbar-nav navbar-right" active-link>
    <li class="nav active"><a href="home">Home</a></li>
    <li class="nav"><a href="foo">Foo</a></li>
    <li class="nav"><a href="bar">Bar</a></li>
</ul>

#8


5  

I use ng-class directive with $location to achieve it.

我使用带有$location的ng类指令来实现它。

<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;
}]);

#9


5  

If you are working with Angular router, the RouterLinkActive directive can be used really elegantly:

如果你使用的是角路由器,那么RouterLinkActive指令可以非常优雅地使用:

<ul class="navbar-nav">
  <li class="nav-item"><a class="nav-link" routerLink="home" routerLinkActive="active">Home</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="gallery" routerLinkActive="active">Gallery</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="pricing" routerLinkActive="active">Prices</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="contact" routerLinkActive="active">Contact</a></li>
</ul>

#10


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. 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.

在开发期间,我每隔一段时间就会使用条件语句进行GUI样式化,因为这比创建指令要快一些。我不能告诉你一个实例,尽管它们实际上在代码库中保存了很长时间。最后我要么把它变成一个指令,要么找到更好的方法来解决这个问题。

#11


4  

If you use ui-router, the following example should satisfy your needs based on @DanPantry's comment on the accepted answer without adding any controller-side code:

如果您使用ui-router,以下示例应该根据@DanPantry对已接受的答案的注释满足您的需求,而不添加任何控制器端代码:

<div class="collapse navbar-collapse" ng-controller="HeaderController">
    <ul class="nav navbar-nav">
        <li ui-sref-active="active"><a ui-sref="app.home()" href="/">Home</a></li>
        <li ui-sref-active="active"><a ui-sref="app.dogs()" href="/dogs">Dogs</a></li>
        <li ui-sref-active="active"><a ui-sref="app.cats()" href="/cats">Cats</a></li>
    </ul>
</div>
<div ng-view></div>

You can check the docs for more info on it.

你可以在文档中找到更多的信息。

#12


3  

If you would rather not use AngularStrap then this directive should do the trick!. This is a modification of https://*.com/a/16231859/910764.

如果你宁愿不使用天使带,那么这个指令应该做的窍门!这是对https://*.com/a/16231859/910764的修改。

JavaScript

JavaScript

angular.module('myApp').directive('bsNavbar', ['$location', function ($location) {
  return {
    restrict: 'A',
    link: function postLink(scope, element) {
      scope.$watch(function () {
        return $location.path();
      }, function (path) {
        angular.forEach(element.children(), (function (li) {
          var $li = angular.element(li),
            regex = new RegExp('^' + $li.attr('data-match-route') + '$', 'i'),
            isActive = regex.test(path);
          $li.toggleClass('active', isActive);
        }));
      });
    }
  };
}]);

HTML

HTML

<ul class="nav navbar-nav" bs-navbar>
  <li data-match-route="/home"><a href="#/home">Home</a></li>
  <li data-match-route="/about"><a href="#/about">About</a></li>
</ul>

Note: The above HTML classes assume you are using Bootstrap 3.x

注意:上面的HTML类假设您正在使用Bootstrap 3.x

#13


3  

Heres my take on it. A little of a combination of answers found on this post. I had a slightly different case, so my solution involves separating the menu into its own template to be used within the Directive Definition Ojbect then add my navbar to the page I needed it on. Basically, I had a login page that I didnt want to include my menu on, so I used ngInclude and insert this directive when logged in:

这是我的看法。在这篇文章中找到一些答案的组合。我有一个稍微不同的情况,所以我的解决方案是将菜单分离到它自己的模板中,然后将导航条添加到我需要它的页面中。基本上,我有一个不想包含菜单的登录页面,所以我使用了ngInclude并在登录时插入这个指令:

DIRECTIVE:

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;

        }
    }
 }
});

DIRECTIVE TEMPLATE (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 WHICH INCLUDES THE DIRECTIVE

<comp-navbar/>

Hope this helps

希望这有助于

#14


2  

Extending myl answer, I needed this to handle an structure like this.

扩展myl答案,我需要这个来处理这样的结构。

-index

指数

-events<-active
---event-list
---event-edit
---event-map <-clicked

-events<-active -事件列表-事件编辑-事件映射<-click

-places
---place-list
---place-edit
---place-map

————-place-list -place-edit——-place-map

so instead of matching, I had to use indexOf, in order to validate children links which are formatted to match the condition. So for 'events':

因此,我必须使用indexOf而不是匹配,以验证为匹配条件而格式化的子链接。所以对于“事件”:

<li ng-class="{ active: isActive('/event')}" class="divider-vertical dropdown">


function NavController($scope, $location) { 
$scope.isActive = function (viewLocation) {
    var s=false;
    if($location.path().indexOf(viewLocation) != -1){
     s = true;
    }
    return s;
};}

#15


2  

This is a simple solution

这是一个简单的解决方案

<ul class="nav navbar-nav navbar-right navbar-default menu">
  <li ng-class="menuIndice == 1 ? 'active':''">
    <a ng-click="menuIndice = 1" href="#/item1">item1</a>
  </li>
  <li ng-class="menuIndice == 2 ? 'active':''">
    <a ng-click="menuIndice = 2" href="#/item2">item2</a>
  </li>
  <li ng-class="menuIndice == 3 ? 'active':''">
    <a ng-click="menuIndice = 3" href="#/item3">item3</a>
  </li>
</ul>

#16


1  

In conjunction with @Olivier's AngularStrap answer, I also implemented kevinknelson's answer from: https://github.com/twbs/bootstrap/issues/9013.

结合@Olivier的AngularStrap回答,我还实现了kevinknelson的回答:https://github.com/twbs/bootstrap/issues/9013。

Natively, the Bootstrap3 navbar was not designed for a single-page (eg Angular) application and thus the menu when on a small screen was not collapsing upon click.

在本地,Bootstrap3 navbar不是为单页应用程序设计的,因此在小屏幕上单击时菜单不会崩溃。

#17


1  

JavaScript

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

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>

#18


1  

Thanks to @Pylinux. I have used his technique and also modified it to support "one" level of drop down menu (sub ul/li), as that is what I needed. See it in action in the fiddle link below.

感谢@Pylinux。我使用了他的技术,并修改了它来支持下拉菜单的“一个”级别(sub - ul/li),这正是我需要的。请看下面的小提琴链接。

Updated Fiddle based on pylinux's answer - http://jsfiddle.net/abhatia/en4qxw6g/

基于pylinux的答案更新了小提琴——http://jsfiddle.net/abhatia/en4qxw6g/

I made the following three changes, in order to support one level drop down menu:
1. Added a class value of dd (dropdown) for "a" element under li which needs to have sub ul list.

我做了以下三个变化,以支持一个水平下拉菜单:1。在li下为“a”元素添加了一个dd(下拉)的类值,该元素需要有子ul列表。

         <li><a class="dd">This link points to #/fun5</a>
          <ul>
            <li><a href="#/fun6?some=data">This link points to #/fun6</a>
            </li>
            <li><a href="#/fun7?some=data">This link points to #/fun7</a>
            </li>
            <li><a href="#/fun8?some=data">This link points to #/fun8</a>
            </li>
            <li><a href="#/fun9?some=data">This link points to #/fun9</a>
            </li>
          </ul>
        </li>


2. Updated Javascript to add the following new logic.

2。更新Javascript以添加以下新逻辑。

 if(angular.element(li).parent().parent().children('a').hasClass("dd"))
 {angular.element(li).parent().parent().children('a.dd').addClass('active');}


3. Updated CSS to the add the following:

3所示。更新后的CSS添加如下:

a.active {background-color:red;}

Hopefully this will be helpful to someone looking to implement single level dropdown menu.

希望这对那些希望实现单级下拉菜单的人有帮助。

#19


0  

You can also use this active-link directive https://*.com/a/23138152/1387163

您还可以使用这个活动链接指令https://*.com/a/23138152/1387163。

Parent li will get active class when location matches /url:

当位置匹配/url:

<li>
    <a href="#!/url" active-link active-link-parent>
</li>

#20


0  

I suggest using a directive on a link. Here is the fiddle.

我建议在链接上使用一个指令。这是小提琴。

But its not perfect yet. Watch out for the hashbangs ;)

但它还不完美。关注# # # # # # # # #

Here is the javascript for directive:

下面是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);
          }
        });
      }
    };
  }]);

and here is how it would be used in html:

以下是它在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>

afterwards styling with css:

后来用css样式:

.active{ color:red; }

#21


0  

Just to add my two cents in the debate I have made a pure angular module (no jquery), and it will also work with hash urls containing data. (i.g. #/this/is/path?this=is&some=data)

为了在辩论中增加我的观点,我制作了一个纯角度模块(没有jquery),它还可以处理包含数据的散列url。(专营# /这个/ /路径?这=一些=数据)

You just add the module as a dependency and auto-active to one of the ancestors of the menu. Like this:

您只需将模块添加为依赖项并将其自动激活到菜单的一个祖先。是这样的:

<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>

And the module look like this:

这个模块是这样的:

(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);
            }
        }
    }]);
}());

* (You can of course just use the directive part)

*(你当然可以使用指令部分)

** It's also worth noticing that this doesn't work for empty hashes (i.g. example.com/# or just example.com) it needs to have at least example.com/#/ or just example.com#/. But this happens automatically with ngResource and the like.

同样值得注意的是,这对空散列(例如example.com/#或example.com)不起作用,它至少需要有example.com/#/或example.com#/。但是这在ngResource之类的东西上是自动发生的。

#22


0  

This did the trick for me:

这对我起了作用:

  var domain = '{{ DOMAIN }}'; // www.example.com or dev.example.com
  var domain_index =  window.location.href.indexOf(domain);
  var long_app_name = window.location.href.slice(domain_index+domain.length+1); 
  // this turns http://www.example.com/whatever/whatever to whatever/whatever
  app_name = long_app_name.slice(0, long_app_name.indexOf('/')); 
  //now you are left off with just the first whatever which is usually your app name

then you use jquery(works with angular too) to add class active

然后使用jquery(也可以使用角)来添加类活动。

$('nav a[href*="' + app_name+'"]').closest('li').addClass('active');

and of course the css:

当然还有css:

.active{background:red;}

this works if you have your html like this:

如果你有这样的html,这是可行的:

<ul><li><a href="/ee">ee</a></li><li><a href="/dd">dd</a></li></ul>

this will atumatically add class active using the page url and color your background to red if your in www.somesite.com/ee thaen ee is the 'app' and it will be active

如果你的www.somesite.com/ee是“app”,它将会是活动的

#23


0  

This is long answered but I thought I'd share my way:

这句话回答得很长,但我想我可以分享我的想法:

.run(function($rootScope, $state){
 $rootScope.$state = $state;
});

Template:

模板:

<ul class="nav navbar-nav">
    <li ng-class="{ active: $state.contains('View1') }"><a href="...">View 1</a></li>
    <li ng-class="{ active: $state.contains('View2') }"><a href="...">View 2</a></li>
    <li ng-class="{ active: $state.contains('View3') }"><a href="...">View 3</a></li>
</ul>

For those using ui-router:

对于那些使用ui-router:

<ul class="nav navbar-nav">
        <li ui-sref-active="active"><a href="...">View 1</a></li>
        <li ui-sref-active="active"><a href="...">View 2</a></li>
        <li ui-sref-active="active"><a href="...">View 3</a></li>
</ul>

For exact match (eg nested states?) use $state.name === 'full/path/to/state' or ui-sref-active-eq="active"

对于精确匹配(如嵌套状态?)使用$ status .name == 'full/path/to/state'或ui-sref-active-eq="active"

#24


0  

Here's another solution for anyone who might be interested. The advantage of this is it has fewer dependencies. Heck, it works without a web server too. So it's completely client-side.

对于任何可能感兴趣的人,这里有另一个解决方案。这样做的好处是它的依赖性更小。见鬼,它也没有网络服务器。这是完全的客户端。

HTML:

HTML:

<nav class="navbar navbar-inverse" ng-controller="topNavBarCtrl"">
<div class="container-fluid">
    <div class="navbar-header">
        <a class="navbar-brand" href="#"><span class="glyphicon glyphicon-home" aria-hidden="true"></span></a>
    </div>
    <ul class="nav navbar-nav">
        <li ng-click="selectTab()" ng-class="getTabClass()"><a href="#">Home</a></li>
        <li ng-repeat="tab in tabs" ng-click="selectTab(tab)" ng-class="getTabClass(tab)"><a href="#">{{ tab }}</a></li>
    </ul>
</div>

Explanation:

解释:

Here we are generating the links dynamically from an angularjs model using the directive ng-repeat. Magic happens with the methods selectTab() and getTabClass() defined in the controller for this navbar presented below.

在这里,我们使用指令ng-repeat从angularjs模型动态生成链接。对于下面给出的这个导航条,在控制器中定义的selectTab()和getTabClass()方法具有神奇的作用。

Controller:

控制器:

angular.module("app.NavigationControllersModule", [])

// Constant named 'activeTab' holding the value 'active'. We will use this to set the class name of the <li> element that is selected.
.constant("activeTab", "active")

.controller("topNavBarCtrl", function($scope, activeTab){
    // Model used for the ng-repeat directive in the template.
    $scope.tabs = ["Page 1", "Page 2", "Page 3"];

    var selectedTab = null;

    // Sets the selectedTab.
    $scope.selectTab = function(newTab){
       selectedTab = newTab;
    };

    // Sets class of the selectedTab to 'active'.
    $scope.getTabClass = function(tab){
       return selectedTab == tab ? activeTab : "";
    };
});

Explanation:

解释:

selectTab() method is called using ng-click directive. So when the link is clicked, the variable selectedTab is set to the name of this link. In the HTML you can see that this method is called without any argument for Home tab so that it will be highlighted when the page loads.

selectTab()方法是使用ng-click指令调用的。所以当链接被单击时,变量selectedTab被设置为该链接的名称。在HTML中,您可以看到这个方法被调用时没有任何Home选项卡的参数,因此当页面加载时它将被突出显示。

The getTabClass() method is called via ng-class directive in the HTML. This method checks if the tab it is in is the same as the value of the selectedTab variable. If true, it returns "active" else returns "" which is applied as the class name by ng-class directive. Then whatever css you have applied to class active will be applied to the selected tab.

getTabClass()方法在HTML中通过ng类指令调用。这个方法检查它所在的选项卡是否与selectedTab变量的值相同。如果是true,它将返回“active”else返回“”,这是由ng类指令应用的类名。然后,您对class active应用的任何css都将应用到所选的选项卡。

#25


0  

Just you'll have to add the required active-class with required color code.

只需添加所需的活动类和所需的颜色代码。

Ex: ng-class="{'active': currentNavSelected}" ng-click="setNav"

例:ng-class = " {“活跃”:currentNavSelected }”ng-click =“setNav”

#1


585  

A very elegant way is to use ng-controller to run a single controller outside of the ng-view:

一种非常优雅的方式是使用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>

and include in controllers.js:

在controllers.js,包括:

function HeaderController($scope, $location) 
{ 
    $scope.isActive = function (viewLocation) { 
        return viewLocation === $location.path();
    };
}

#2


50  

I just wrote a directive to handle this, so you can simply add the attribute bs-active-link to the parent <ul> element, and any time the route changed, it will find the matching link, and add the active class to the corresponding <li>.

我刚刚编写了一个指令来处理这个问题,所以您可以简单地将属性bs-active-link添加到父元素

    元素中,并且只要路由改变,它就会找到匹配的链接,并将活动类添加到相应的
  • 中。

  • 中。

You can see it in action here: http://jsfiddle.net/8mcedv3b/

您可以在这里看到它的作用:http://jsfiddle.net/8mcedv3b/

Example HTML:

示例HTML:

<ul class="nav navbar-nav" bs-active-link>
  <li><a href="/home">Home</a></li>
  <li><a href="/contact">Contact</a></li>
</ul>

Javascript:

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');   
                };
            });     
        });
    }
}
}]);

#3


38  

You can have a look at AngularStrap, the navbar directive seems to be what you are looking for:

你可以看看角带,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:

使用这个指令:

  1. Download AngularStrap from http://mgcrea.github.io/angular-strap/

    从http://mgcrea.github.io/angular-strap/下载AngularStrap

  2. Include the script on your page after bootstrap.js:
    <script src="lib/angular-strap.js"></script>

    在引导之后将脚本包含在页面上。js:< script src = " lib / angular-strap.js " > < /脚本>

  3. Add the directives to your module:
    angular.module('myApp', ['$strap.directives'])

    向模块添加指令:角度。模块(“myApp”,[' strap.directives美元'])

  4. Add the directive to your navbar:
    <div class="navbar" bs-navbar>

    向导航条中添加指令:

  5. Add regexes on each nav item:
    <li data-match-route="/about"><a href="#/about">About</a></li>

    在每个nav项目上增加regexes:

  6. about
  7. 关于

#4


32  

Here's a simple approach that works well with 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;
};

#5


8  

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. Additionally, you can implement a listener on the $routeChangeSuccess method of the $route object to listen for the successful completion of a route change.

这里有一个简单的解决方案,您应该能够添加到任何项目中。您可以在配置路由时添加“pageKey”或其他一些属性,您可以使用这些属性来进行键合。此外,您可以在$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.

当处理程序触发时,您将获得页面键,并使用该键定位需要为该页“活动”的元素,然后应用活动类。

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类将它们全部关闭,而我使用. pagekey_ {PAGEKEY}将它们单独打开。将它们全部切换为非活动的,将被认为是一种幼稚的方法,您可以使用前面的路由来使活动项处于非活动状态,从而获得更好的性能,或者您可以将jquery选择器更改为只选择不活动的活动项。使用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

给出一个引导导航条

<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>

#6


7  

You can actually use angular-ui-utils' ui-route directive:

你可以使用angular-ui-utils的ui-route指令:

<a ui-route ng-href="/">Home</a>
<a ui-route ng-href="/about">About</a>
<a ui-route ng-href="/contact">Contact</a>

or:

或者:

Header Controller

/**
 * Header controller
 */
angular.module('myApp')
  .controller('HeaderCtrl', function ($scope) {
    $scope.menuItems = [
      {
        name: 'Home',
        url:  '/',
        title: 'Go to homepage.'
      },
      {
        name:   'About',
        url:    '/about',
        title:  'Learn about the project.'
      },
      {
        name:   'Contact',
        url:    '/contact',
        title:  'Contact us.'
      }
    ];
  });

Index page

<!-- index.html: -->
<div class="header" ng-controller="HeaderCtrl">
  <ul class="nav navbar-nav navbar-right">
    <li ui-route="{{menuItem.url}}" ng-class="{active: $uiRoute}"
      ng-repeat="menuItem in menuItems">
      <a ng-href="#{{menuItem.url}}" title="{{menuItem.title}}">
        {{menuItem.name}}
      </a>
    </li>
  </ul>
</div>

If you're using ui-utils, you may also be interested in ui-router for managing partial/nested views.

如果您使用的是ui-utils,您可能也会对ui-router感兴趣,用于管理部分/嵌套视图。

#7


6  

I find all of these answers a bit over complicated for me, sorry. So I have created a small directive that should work on a per navbar basis:

我发现这些答案对我来说有点复杂,抱歉。所以我创建了一个小指令,应该在每个导航条的基础上工作:

app.directive('activeLink', function () {
    return {
        link: function (scope, element, attrs) {
            element.find('.nav a').on('click', function () {
                angular.element(this)
                    .parent().siblings('.active')
                    .removeClass('active');
                angular.element(this)
                    .parent()
                    .addClass('active');
            });
        }
    };
});

Usage:

用法:

<ul class="nav navbar-nav navbar-right" active-link>
    <li class="nav active"><a href="home">Home</a></li>
    <li class="nav"><a href="foo">Foo</a></li>
    <li class="nav"><a href="bar">Bar</a></li>
</ul>

#8


5  

I use ng-class directive with $location to achieve it.

我使用带有$location的ng类指令来实现它。

<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;
}]);

#9


5  

If you are working with Angular router, the RouterLinkActive directive can be used really elegantly:

如果你使用的是角路由器,那么RouterLinkActive指令可以非常优雅地使用:

<ul class="navbar-nav">
  <li class="nav-item"><a class="nav-link" routerLink="home" routerLinkActive="active">Home</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="gallery" routerLinkActive="active">Gallery</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="pricing" routerLinkActive="active">Prices</a></li>
  <li class="nav-item"><a class="nav-link" routerLink="contact" routerLinkActive="active">Contact</a></li>
</ul>

#10


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. 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.

在开发期间,我每隔一段时间就会使用条件语句进行GUI样式化,因为这比创建指令要快一些。我不能告诉你一个实例,尽管它们实际上在代码库中保存了很长时间。最后我要么把它变成一个指令,要么找到更好的方法来解决这个问题。

#11


4  

If you use ui-router, the following example should satisfy your needs based on @DanPantry's comment on the accepted answer without adding any controller-side code:

如果您使用ui-router,以下示例应该根据@DanPantry对已接受的答案的注释满足您的需求,而不添加任何控制器端代码:

<div class="collapse navbar-collapse" ng-controller="HeaderController">
    <ul class="nav navbar-nav">
        <li ui-sref-active="active"><a ui-sref="app.home()" href="/">Home</a></li>
        <li ui-sref-active="active"><a ui-sref="app.dogs()" href="/dogs">Dogs</a></li>
        <li ui-sref-active="active"><a ui-sref="app.cats()" href="/cats">Cats</a></li>
    </ul>
</div>
<div ng-view></div>

You can check the docs for more info on it.

你可以在文档中找到更多的信息。

#12


3  

If you would rather not use AngularStrap then this directive should do the trick!. This is a modification of https://*.com/a/16231859/910764.

如果你宁愿不使用天使带,那么这个指令应该做的窍门!这是对https://*.com/a/16231859/910764的修改。

JavaScript

JavaScript

angular.module('myApp').directive('bsNavbar', ['$location', function ($location) {
  return {
    restrict: 'A',
    link: function postLink(scope, element) {
      scope.$watch(function () {
        return $location.path();
      }, function (path) {
        angular.forEach(element.children(), (function (li) {
          var $li = angular.element(li),
            regex = new RegExp('^' + $li.attr('data-match-route') + '$', 'i'),
            isActive = regex.test(path);
          $li.toggleClass('active', isActive);
        }));
      });
    }
  };
}]);

HTML

HTML

<ul class="nav navbar-nav" bs-navbar>
  <li data-match-route="/home"><a href="#/home">Home</a></li>
  <li data-match-route="/about"><a href="#/about">About</a></li>
</ul>

Note: The above HTML classes assume you are using Bootstrap 3.x

注意:上面的HTML类假设您正在使用Bootstrap 3.x

#13


3  

Heres my take on it. A little of a combination of answers found on this post. I had a slightly different case, so my solution involves separating the menu into its own template to be used within the Directive Definition Ojbect then add my navbar to the page I needed it on. Basically, I had a login page that I didnt want to include my menu on, so I used ngInclude and insert this directive when logged in:

这是我的看法。在这篇文章中找到一些答案的组合。我有一个稍微不同的情况,所以我的解决方案是将菜单分离到它自己的模板中,然后将导航条添加到我需要它的页面中。基本上,我有一个不想包含菜单的登录页面,所以我使用了ngInclude并在登录时插入这个指令:

DIRECTIVE:

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;

        }
    }
 }
});

DIRECTIVE TEMPLATE (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 WHICH INCLUDES THE DIRECTIVE

<comp-navbar/>

Hope this helps

希望这有助于

#14


2  

Extending myl answer, I needed this to handle an structure like this.

扩展myl答案,我需要这个来处理这样的结构。

-index

指数

-events<-active
---event-list
---event-edit
---event-map <-clicked

-events<-active -事件列表-事件编辑-事件映射<-click

-places
---place-list
---place-edit
---place-map

————-place-list -place-edit——-place-map

so instead of matching, I had to use indexOf, in order to validate children links which are formatted to match the condition. So for 'events':

因此,我必须使用indexOf而不是匹配,以验证为匹配条件而格式化的子链接。所以对于“事件”:

<li ng-class="{ active: isActive('/event')}" class="divider-vertical dropdown">


function NavController($scope, $location) { 
$scope.isActive = function (viewLocation) {
    var s=false;
    if($location.path().indexOf(viewLocation) != -1){
     s = true;
    }
    return s;
};}

#15


2  

This is a simple solution

这是一个简单的解决方案

<ul class="nav navbar-nav navbar-right navbar-default menu">
  <li ng-class="menuIndice == 1 ? 'active':''">
    <a ng-click="menuIndice = 1" href="#/item1">item1</a>
  </li>
  <li ng-class="menuIndice == 2 ? 'active':''">
    <a ng-click="menuIndice = 2" href="#/item2">item2</a>
  </li>
  <li ng-class="menuIndice == 3 ? 'active':''">
    <a ng-click="menuIndice = 3" href="#/item3">item3</a>
  </li>
</ul>

#16


1  

In conjunction with @Olivier's AngularStrap answer, I also implemented kevinknelson's answer from: https://github.com/twbs/bootstrap/issues/9013.

结合@Olivier的AngularStrap回答,我还实现了kevinknelson的回答:https://github.com/twbs/bootstrap/issues/9013。

Natively, the Bootstrap3 navbar was not designed for a single-page (eg Angular) application and thus the menu when on a small screen was not collapsing upon click.

在本地,Bootstrap3 navbar不是为单页应用程序设计的,因此在小屏幕上单击时菜单不会崩溃。

#17


1  

JavaScript

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

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>

#18


1  

Thanks to @Pylinux. I have used his technique and also modified it to support "one" level of drop down menu (sub ul/li), as that is what I needed. See it in action in the fiddle link below.

感谢@Pylinux。我使用了他的技术,并修改了它来支持下拉菜单的“一个”级别(sub - ul/li),这正是我需要的。请看下面的小提琴链接。

Updated Fiddle based on pylinux's answer - http://jsfiddle.net/abhatia/en4qxw6g/

基于pylinux的答案更新了小提琴——http://jsfiddle.net/abhatia/en4qxw6g/

I made the following three changes, in order to support one level drop down menu:
1. Added a class value of dd (dropdown) for "a" element under li which needs to have sub ul list.

我做了以下三个变化,以支持一个水平下拉菜单:1。在li下为“a”元素添加了一个dd(下拉)的类值,该元素需要有子ul列表。

         <li><a class="dd">This link points to #/fun5</a>
          <ul>
            <li><a href="#/fun6?some=data">This link points to #/fun6</a>
            </li>
            <li><a href="#/fun7?some=data">This link points to #/fun7</a>
            </li>
            <li><a href="#/fun8?some=data">This link points to #/fun8</a>
            </li>
            <li><a href="#/fun9?some=data">This link points to #/fun9</a>
            </li>
          </ul>
        </li>


2. Updated Javascript to add the following new logic.

2。更新Javascript以添加以下新逻辑。

 if(angular.element(li).parent().parent().children('a').hasClass("dd"))
 {angular.element(li).parent().parent().children('a.dd').addClass('active');}


3. Updated CSS to the add the following:

3所示。更新后的CSS添加如下:

a.active {background-color:red;}

Hopefully this will be helpful to someone looking to implement single level dropdown menu.

希望这对那些希望实现单级下拉菜单的人有帮助。

#19


0  

You can also use this active-link directive https://*.com/a/23138152/1387163

您还可以使用这个活动链接指令https://*.com/a/23138152/1387163。

Parent li will get active class when location matches /url:

当位置匹配/url:

<li>
    <a href="#!/url" active-link active-link-parent>
</li>

#20


0  

I suggest using a directive on a link. Here is the fiddle.

我建议在链接上使用一个指令。这是小提琴。

But its not perfect yet. Watch out for the hashbangs ;)

但它还不完美。关注# # # # # # # # #

Here is the javascript for directive:

下面是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);
          }
        });
      }
    };
  }]);

and here is how it would be used in html:

以下是它在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>

afterwards styling with css:

后来用css样式:

.active{ color:red; }

#21


0  

Just to add my two cents in the debate I have made a pure angular module (no jquery), and it will also work with hash urls containing data. (i.g. #/this/is/path?this=is&some=data)

为了在辩论中增加我的观点,我制作了一个纯角度模块(没有jquery),它还可以处理包含数据的散列url。(专营# /这个/ /路径?这=一些=数据)

You just add the module as a dependency and auto-active to one of the ancestors of the menu. Like this:

您只需将模块添加为依赖项并将其自动激活到菜单的一个祖先。是这样的:

<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>

And the module look like this:

这个模块是这样的:

(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);
            }
        }
    }]);
}());

* (You can of course just use the directive part)

*(你当然可以使用指令部分)

** It's also worth noticing that this doesn't work for empty hashes (i.g. example.com/# or just example.com) it needs to have at least example.com/#/ or just example.com#/. But this happens automatically with ngResource and the like.

同样值得注意的是,这对空散列(例如example.com/#或example.com)不起作用,它至少需要有example.com/#/或example.com#/。但是这在ngResource之类的东西上是自动发生的。

#22


0  

This did the trick for me:

这对我起了作用:

  var domain = '{{ DOMAIN }}'; // www.example.com or dev.example.com
  var domain_index =  window.location.href.indexOf(domain);
  var long_app_name = window.location.href.slice(domain_index+domain.length+1); 
  // this turns http://www.example.com/whatever/whatever to whatever/whatever
  app_name = long_app_name.slice(0, long_app_name.indexOf('/')); 
  //now you are left off with just the first whatever which is usually your app name

then you use jquery(works with angular too) to add class active

然后使用jquery(也可以使用角)来添加类活动。

$('nav a[href*="' + app_name+'"]').closest('li').addClass('active');

and of course the css:

当然还有css:

.active{background:red;}

this works if you have your html like this:

如果你有这样的html,这是可行的:

<ul><li><a href="/ee">ee</a></li><li><a href="/dd">dd</a></li></ul>

this will atumatically add class active using the page url and color your background to red if your in www.somesite.com/ee thaen ee is the 'app' and it will be active

如果你的www.somesite.com/ee是“app”,它将会是活动的

#23


0  

This is long answered but I thought I'd share my way:

这句话回答得很长,但我想我可以分享我的想法:

.run(function($rootScope, $state){
 $rootScope.$state = $state;
});

Template:

模板:

<ul class="nav navbar-nav">
    <li ng-class="{ active: $state.contains('View1') }"><a href="...">View 1</a></li>
    <li ng-class="{ active: $state.contains('View2') }"><a href="...">View 2</a></li>
    <li ng-class="{ active: $state.contains('View3') }"><a href="...">View 3</a></li>
</ul>

For those using ui-router:

对于那些使用ui-router:

<ul class="nav navbar-nav">
        <li ui-sref-active="active"><a href="...">View 1</a></li>
        <li ui-sref-active="active"><a href="...">View 2</a></li>
        <li ui-sref-active="active"><a href="...">View 3</a></li>
</ul>

For exact match (eg nested states?) use $state.name === 'full/path/to/state' or ui-sref-active-eq="active"

对于精确匹配(如嵌套状态?)使用$ status .name == 'full/path/to/state'或ui-sref-active-eq="active"

#24


0  

Here's another solution for anyone who might be interested. The advantage of this is it has fewer dependencies. Heck, it works without a web server too. So it's completely client-side.

对于任何可能感兴趣的人,这里有另一个解决方案。这样做的好处是它的依赖性更小。见鬼,它也没有网络服务器。这是完全的客户端。

HTML:

HTML:

<nav class="navbar navbar-inverse" ng-controller="topNavBarCtrl"">
<div class="container-fluid">
    <div class="navbar-header">
        <a class="navbar-brand" href="#"><span class="glyphicon glyphicon-home" aria-hidden="true"></span></a>
    </div>
    <ul class="nav navbar-nav">
        <li ng-click="selectTab()" ng-class="getTabClass()"><a href="#">Home</a></li>
        <li ng-repeat="tab in tabs" ng-click="selectTab(tab)" ng-class="getTabClass(tab)"><a href="#">{{ tab }}</a></li>
    </ul>
</div>

Explanation:

解释:

Here we are generating the links dynamically from an angularjs model using the directive ng-repeat. Magic happens with the methods selectTab() and getTabClass() defined in the controller for this navbar presented below.

在这里,我们使用指令ng-repeat从angularjs模型动态生成链接。对于下面给出的这个导航条,在控制器中定义的selectTab()和getTabClass()方法具有神奇的作用。

Controller:

控制器:

angular.module("app.NavigationControllersModule", [])

// Constant named 'activeTab' holding the value 'active'. We will use this to set the class name of the <li> element that is selected.
.constant("activeTab", "active")

.controller("topNavBarCtrl", function($scope, activeTab){
    // Model used for the ng-repeat directive in the template.
    $scope.tabs = ["Page 1", "Page 2", "Page 3"];

    var selectedTab = null;

    // Sets the selectedTab.
    $scope.selectTab = function(newTab){
       selectedTab = newTab;
    };

    // Sets class of the selectedTab to 'active'.
    $scope.getTabClass = function(tab){
       return selectedTab == tab ? activeTab : "";
    };
});

Explanation:

解释:

selectTab() method is called using ng-click directive. So when the link is clicked, the variable selectedTab is set to the name of this link. In the HTML you can see that this method is called without any argument for Home tab so that it will be highlighted when the page loads.

selectTab()方法是使用ng-click指令调用的。所以当链接被单击时,变量selectedTab被设置为该链接的名称。在HTML中,您可以看到这个方法被调用时没有任何Home选项卡的参数,因此当页面加载时它将被突出显示。

The getTabClass() method is called via ng-class directive in the HTML. This method checks if the tab it is in is the same as the value of the selectedTab variable. If true, it returns "active" else returns "" which is applied as the class name by ng-class directive. Then whatever css you have applied to class active will be applied to the selected tab.

getTabClass()方法在HTML中通过ng类指令调用。这个方法检查它所在的选项卡是否与selectedTab变量的值相同。如果是true,它将返回“active”else返回“”,这是由ng类指令应用的类名。然后,您对class active应用的任何css都将应用到所选的选项卡。

#25


0  

Just you'll have to add the required active-class with required color code.

只需添加所需的活动类和所需的颜色代码。

Ex: ng-class="{'active': currentNavSelected}" ng-click="setNav"

例:ng-class = " {“活跃”:currentNavSelected }”ng-click =“setNav”