Here is yet another directive to highlight active links.
Key features:
- Works fine with href that contains dynamic angular expressions
- Compatible with hash-bang navigation
- Compatible with Bootstrap where active class should be applied to parent li not the link itself
- Allows make link active if any nested path is active
- Allows make link disabled if it is not active
Code:
.directive('activeLink', ['$location',
function($location) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var path = attrs.activeLink ? 'activeLink' : 'href';
var target = angular.isDefined(attrs.activeLinkParent) ? elem.parent() : elem;
var disabled = angular.isDefined(attrs.activeLinkDisabled) ? true : false;
var nested = angular.isDefined(attrs.activeLinkNested) ? true : false;
function inPath(needle, haystack) {
var current = (haystack == needle);
if (nested) {
current |= (haystack.indexOf(needle + '/') == 0);
}
return current;
}
function toggleClass(linkPath, locationPath) {
// remove hash prefix and trailing slashes
linkPath = linkPath ? linkPath.replace(/^#!/, '').replace(/\/+$/, '') : '';
locationPath = locationPath.replace(/\/+$/, '');
if (linkPath && inPath(linkPath, locationPath)) {
target.addClass('active');
if (disabled) {
target.removeClass('disabled');
}
} else {
target.removeClass('active');
if (disabled) {
target.addClass('disabled');
}
}
}
// watch if attribute value changes / evaluated
attrs.$observe(path, function(linkPath) {
toggleClass(linkPath, $location.path());
});
// watch if location changes
scope.$watch(
function() {
return $location.path();
},
function(newPath) {
toggleClass(attrs[path], newPath);
}
);
}
};
}
]);
Usage:
Simple example with angular expression, lets say $scope.var = 2, then link will be active if location is /url/2 :
<a href="#!/url/{{var}}" active-link>
Bootstrap example, parent li will get active class:
<li>
<a href="#!/url" active-link active-link-parent>
</li>
Example with nested urls, link will be active if any nested url is active (i.e. /url/1, /url/2, url/1/2/...)
<a href="#!/url" active-link active-link-nested>
Complex example, link points to one url (/url1) but will be active if another is selected (/url2):
<a href="#!/url1" active-link="#!/url2" active-link-nested>
Example with disabled link, if it is not active it will have 'disabled' class:
<a href="#!/url" active-link active-link-disabled>
All active-link-* attributes can be used in any combination, so very complex conditions could be implemented.