How to set bootstrap navbar active class with Angular JS?

user1876508 picture user1876508 · Apr 24, 2013 · Viewed 235.1k times · Source

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

  1. #/ for home
  2. #/about for the about page
  3. #/contact for the contact page

Answer

myl picture myl · Sep 1, 2013

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>
    </ul>
</div>
<div ng-view></div>

and include in controllers.js:

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