'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: * */ 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 element (linkElement) and the surounding
  • 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'); } }); }); } }; });