Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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

1 Answer

0 votes
by (106k points)
edited by

To set bootstrap navbar active class with AngularJS there is a very elegant way is to use ng-controller to run a single controller outside of the ng-view see the code below:-

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

Looking for Angularjs material from basics! Refer to this video on Angularjs provided by Intellipaat:

Looking for Angularjs material from basics! Refer to this video on Angularjs provided by Intellipaat:

And include in controllers.js:

function HeaderController($scope, $location) { 

  $scope.isActive = function (viewLocation) { 

    return viewLocation === $location.path(); 

  }; 

}

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...