Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AngularJS directive to mark navigation menu items as active
'use strict';
// <ul nav-menu="active">
// <li><a href="/one">Page One</a></li>
// <li><a href="/two">Page Two</a></li>
// <li><a href="/three">Page Three</a></li>
// </ul>
app.directive('navMenu', function($location) {
return function(scope, element, attrs) {
var links = element.find('a'),
currentLink,
urlMap = {},
activeClass = attrs.navMenu || 'active';
for (var i = links.length - 1; i >= 0; i--) {
var link = angular.element(links[i]);
var url = link.attr('href');
if (url.substring(0,1) === '#') {
urlMap[url.substring(1)] = link;
} else {
urlMap[url] = link;
}
}
scope.$on('$routeChangeStart', function() {
var path = urlMap[$location.path()];
links.parent('li').removeClass(activeClass);
if (path) {
path.parent('li').addClass(activeClass);
}
});
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.