Aqui está mais uma diretiva para destacar links ativos.
Características principais:
- Funciona bem com href que contém expressões angulares dinâmicas
- Compatível com navegação hash-bang
- Compatível com o Bootstrap, em que a classe ativa deve ser aplicada ao li pai, não ao link em si
- Permite ativar o link se algum caminho aninhado estiver ativo
- Permite desativar o link se não estiver ativo
Código:
.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);
}
);
}
};
}
]);
Uso:
Exemplo simples com expressão angular, digamos $ scope.var = 2 , o link estará ativo se o local for / url / 2 :
<a href="#!/url/{{var}}" active-link>
Exemplo de bootstrap, li pai obterá a classe ativa:
<li>
<a href="#!/url" active-link active-link-parent>
</li>
Exemplo com URLs aninhados, o link estará ativo se algum URL aninhado estiver ativo (por exemplo, / url / 1 , / url / 2 , url / 1/2 / ... )
<a href="#!/url" active-link active-link-nested>
Exemplo complexo, o link aponta para um URL ( / url1 ), mas estará ativo se outro for selecionado ( / url2 ):
<a href="#!/url1" active-link="#!/url2" active-link-nested>
Exemplo com link desativado, se não estiver ativo, ele terá a classe 'disabled' :
<a href="#!/url" active-link active-link-disabled>
Todos os atributos active-link- * podem ser usados em qualquer combinação, portanto condições muito complexas podem ser implementadas.