user1876508 user1876508 - 1 year ago 73
AngularJS Question

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
when the angular route is at

  1. #/
    for home

  2. #/about
    for the about page

  3. #/contact
    for the contact page

myl myl
Answer Source

A very elegant way is to use ng-controller to run a single controller outside of the 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>
<div ng-view></div>

and include in controllers.js:

function HeaderController($scope, $location) 
    $scope.isActive = function (viewLocation) { 
        return viewLocation === $location.path();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download