• Home /
  • Blog /
  • How to highlight a current menu item using AngularJS directive
Angular Js By Google

How to highlight a current menu item using AngularJS directive

For one of my projects which is developed using AngularJS, I need to highlight current menu item. This task can be easy solved if the url already known using data-ng-class directive, but if the url constructed using AngularJs ng-class does not work. The menu which I have created with the following code

To solve the task, I decided to create angularJs directive, which I can apply to li tag and attach "active" class if the opened page url match href of the link. Below is my directive code:

The directive name is 'activeLink' and I am going to apply it to li tag, so the template for creating menu now changed to:

I prefix all angularJs directives with data- and I don't need to pass any parameters to my directive, so I left it empty. The code which I create for my angularJs directive do the following: in line [20] I return directiveDefinitionObject, which provides instruction to angularJs compiler. In my case I return only two attributes: restrict - is a string which restrict directive syntax to specific style. In my case 'A' means then style is Attribute: <div my-directive="exp"> </div> and link which is the function, which executed when angularjs directive compiles. The link function is where all action happens and in my case the function is very simple. In line [4] I create a listener on the url in browser navigation string, so as soon as user click to some link and current location will be changed my listener will be called and as a parameter it gets new url. After I have current URL, I look for links children of current element (which is li, the same element where directive applied). After I found 'a' tags I extract link of the tag and ignore first character, which is # sign. Next, after I have link text and url text, I just compare them and if they match, add 'active' class to element (li) or remove it.

Yaplex - Freelance developer - white logo on black background

Yaplex ® is a custom software development company located in Mississauga, Ontario. Yaplex was founded in 2013 and provides website development, mobile development, and custom .NET software development services.

Contact Information

Mississauga, ON, Canada
Phone: +1 647 328 3809
Email: hello@yaplex.com