Skip to content

Instantly share code, notes, and snippets.

@edy
Created September 7, 2014 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edy/4069c31df0b55baff784 to your computer and use it in GitHub Desktop.
Save edy/4069c31df0b55baff784 to your computer and use it in GitHub Desktop.
'use strict';
/**
* frt-nav directive
* should be used within bootstrap navigations to set the 'active' class on current active link (li-element)
* dom should look like this:
* <ul frt-nav>
* <li>
* <a ui-sref="stateName">linkName</a>
* </li>
* </ul>
*/
app.directive('frtNav', function ($rootScope, $state) {
return {
restrict: 'A',
link: function postLink (scope, element) {
// all anchors within frt-nav
var links = element.find('li').find('a');
// whenever the state changes, reset active li element
scope.$on('$stateChangeSuccess', function () {
angular.forEach(links, function (link) {
// the current <a> element (linkElement) and the surounding <li> element (listElement)
var linkElement = angular.element(link);
var listElement = linkElement.parent();
// the state of current link, given by ui-sref attribute
var stateName = linkElement.attr('ui-sref');
// the state of current link gets compared with the app's state (current route)
var stateClass = $state.includes(stateName) ? 'active' : ''; // 'active' is state matches, '' otherwise
// based on calculated stateClass for current link, set or remove 'active' class on sorounding list element
if(stateClass === 'active') {
listElement.addClass('active');
} else {
listElement.removeClass('active');
}
});
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment