SoFunction
Updated on 2025-04-10

Directive in AngularJS makes a menu

Let me tell you how I often write menus:

<ul>
<li data-ng-class="{'active': highlight('/orders')}">
<a href="#/orders">Orders</a>
</li>
</ul> 

Whether the menu item is highlighted depends on the highlight method in the controller.

 = funciton(path){
return $().substr(0, ) === path;
}

It would be simpler if it was directive.

<ul menu-highlighter highlight-class-name="active">
<li><a href="#/customers">Customers</a></li>
<li><a href="#/orders">Customers</a></li>
<li><a href="#/about">Customers</a></li>
</ul> 

Directive is roughly:

(function(){
var injectParams = ['$location'];
var menuHighlighter = function($location){
var link = function(scope, element){
function setActive(){
var path = $();
var className =  || 'active';
if(path){
(('li'), function(li){
//<a href="#/customers">Customers</a>
var anchor = ('a');
//#/customers
var href=(anchor && ) ?  : ('data-href').replace('#','');
//customers
var trimmedHref = (('#/')+1, );
var basePath = (0, );
if(trimmedHref === basePath){
(li).addClass(className);
} else {
(li).removeClass(className);
}
});
} 
}
setActive();
scope.$on('$locationChangeSuccess', setActive);
};
return {
restrict: 'A',
scope: {
highlightClassName: '@'
},
link: link
}
};
menuHighlighter.$inject = injectParams;
('')
.directive('menuHighlighter', menuHighlighter);
}()); 

The above content is related to the creation of a menu for Directive in AngualrJS. I hope it will be helpful to everyone.