Skip to content

Instantly share code, notes, and snippets.

@marco-martins
Created February 9, 2016 15:14
Show Gist options
  • Save marco-martins/8e6027cbd095e71716b1 to your computer and use it in GitHub Desktop.
Save marco-martins/8e6027cbd095e71716b1 to your computer and use it in GitHub Desktop.
AngularJS is-Active link
'use strict';
/**
* @ngdoc directive
* @name onepmApp.directive:isActive
* @description
* # isActive
*/
angular.module('onepmApp')
.directive('isActive', function ($state, $log, $compile) {
return {
restrict: 'A',
scope: true,
compile: function (element, attributes) {
var url = element.find('a[ui-sref]').attr('ui-sref').match(/[a-z.]*/) || [],
bindKlass = attributes.isActive === 'is-active' ? 'active' : attributes.isActive;
element.removeAttr('is-active'); // necessary to avoid infinite compile loop
element.attr('ng-class', '{ "' + bindKlass + '": active }');
function link($scope) {
$scope.url = url[0];
$compile(element)($scope);
}
return link;
},
controller: function ($scope, $rootScope, $timeout) {
function setClass (urlString) {
var url = $scope.url;
$scope.active = !url.indexOf(urlString);
if ( url.split('.')[1] === 'index' && url.split('.')[0] === urlString.split('.')[0]) {
$scope.active = true;
}
}
// After state change
$rootScope.$on('$stateChangeSuccess', function(event, toState){
setClass(toState.name);
});
// Browser refresh
$timeout(function() {
setClass($state.current.name);
}, 500);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment