Attaching persistent active classes to navigation elements in navbar scope (AngularJS) Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Attaching persistent active classes to navigation elements in navbar scope (AngularJS) without wasting too much if your time.

The question is published on by Tutorial Guruji team.

So I have a navigation list element and I want AngularJS to store which tab is active, then add the ‘active’ class to that tab any time a reroute happens. I am trying to simply print the active tab’s name to the log currently. I haven’t linked a function in the ‘link’ option of a directive before, so my syntax may be wrong.

My navigation directive:

navigation.$inject = ['$modal', 'localStorageService', '$log']
  function navigation ($modal, localStorageService, $log) {
    var vm = this;

        return {
          restrict: 'EA',
          templateUrl: '/common/directives/navigation/navigation.template.html',
          link : function ($scope, $log, localStorageService) {
            $scope.setActive = function (tab) {
              $ = tab;

My HTML (one of my ‘pagination’ navigation elements):

<li><a href="/#/cw" ng-click="$scope.setActive('cw')">Connect Wise</a></li>

At this point I’m just trying to access whats in link, and print the variable passed into my directive’s ‘link’ function to the console in the browser.

This seems like it should be very easy but I can’t figure it out for the life of me.

EDIT: I should add, my current approach is based on this: How to define a function inside Angular-js Directive


IMHO this approach is not particularly true to common AngularJS convention. Using a directive for your navigational needs is probably an over-kill.

Generally speaking the community has embraced Angular UI-Router as a solution for your navigation woes.

If you use ui-router you can add a function to the Navigation controller’s scope that checks the $state service for the current state/route to see if the route you”re looking for is currently active.

Even if you are not using ui-router, my advice would be to have a service that tells your application what is your current route and use something like

<a ng-click="goToState('home')" ng-class="{active: isStateActive('home')}">Home</a>

Where $scope.isStateActive(stateName) is the function on your navigation controller’s scope that determines(whether by using ui-router’s $state service or your homegrown service if we are currently in the ‘home’ state and $scope.goToState(stateName) is a function that initiates the state transition

We are here to answer your question about Attaching persistent active classes to navigation elements in navbar scope (AngularJS) - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji