How to add class active to a menu with AngularJS

Now I was building a simple AngularJS site with a menu and ran into the problem of how to highlight the active menu item based on the url. After some research and trial and error I figured the best option is to use a directive. I would simply add an attribute to every list item I like to be watched and compare the current path with the href of the item.

Just add the attribute "is-active-nav" to the link in your menu in the template.

<ul>
  <li><a is-active-nav href="/#/">Home</a></li>`
  <li><a is-active-nav href="/#/lorem">Lorem</a></li>
  <li><a is-active-nav href="/#/ipsum">Ipsum</a></li>
</ul>

In Javascript add a directive. Note that the name of the directive is camel case.

someApp.directive('isActiveNav', [ '$location', function($location) {
return {
 restrict: 'A',
 link: function(scope, element) {
   scope.location = $location;
   scope.$watch('location.path()', function(currentPath) {
     if('/#' + currentPath === element[0].attributes['href'].nodeValue) {
       element.parent().addClass('active');
     } else {
       element.parent().removeClass('active');
     }
   });
 }
 };
}]);

This directive simply watches the location path for changes. If it does, it compares all the href attributes of the menu items with the current location and sets the class "active" to the matching element.

blog comments powered by Disqus