Skip to content

Instantly share code, notes, and snippets.

@edy
Last active May 30, 2018 04:16
Show Gist options
  • Save edy/6954733 to your computer and use it in GitHub Desktop.
Save edy/6954733 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);
}
});
};
});
@xianghongai
Copy link

-- ul.menu-level-1
    -- li.menu-item
        -- h3.menu-title
    -- li.menu-item
        -- h3.menu-header
        -- ul.menu-level-2
            -- li.menu-item
                -- h3.menu-title
            -- li.menu-item
                -- h3.menu-header
                -- ul.menu-level-3
                    -- ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment