Skip to content

Instantly share code, notes, and snippets.

@maragh
Forked from edy/angular-directive-navmenu.js
Created September 23, 2015 20:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maragh/f0f83b610c5e7cd81b4d to your computer and use it in GitHub Desktop.
Save maragh/f0f83b610c5e7cd81b4d to your computer and use it in GitHub Desktop.
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