user1876508 user1876508 - 24 days ago 4
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
class="active"
when the angular route is at


  1. #/
    for home

  2. #/about
    for the about page

  3. #/contact
    for the contact page


myl myl
Answer

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