Angularjs – ui-router active class for parent menu when submenu selected

angular-ui-routerangularjs

I am a newbie to ui-router , i would like to get a menu like below (its not a collapse thing, please see the plnkr )

  1. menu1

    a) submenu1

    b) submenu2

    c) submenu3

  2. menu2

  3. menu3

I managed to get the menus and submenus using the ui-router but not sure about the proper way to use the ui-router and used ui-sref-active="active" active the menu , the problem am facing is when I click on the submenu i would like to get the active to parent also.. ie if I click submenu1 , submenu2 or submneu3 i want to active its parent menu1.

here is the plunker : http://plnkr.co/edit/1kpmUiacrb3Aoo4E19O1?p=preview

Best Answer

There is an updated plunker, which does use the $state.includes method as defined here

the changes are: menu gets controller which puts $state into $scope:

"menu@dashboard": { templateUrl: "menu.html", 
            controller : function ($scope, $state){ $scope.$state = $state },
      },

instead of this:

<li ui-sref-active="active"><a ui-sref=".menu1.submenu1">Menu 1</a></li>
<li ui-sref-active="active"><a ui-sref=".menu2">Menu 2</a></li>
<li ui-sref-active="active"><a ui-sref=".menu3">Menu 3</a></li>

we have to use defintion with ng-class:

<li ng-class="{active:$state.includes('dashboard.menu1')}"><a ui-sref=".menu1.submenu1">Menu 1</a></li>
<li ng-class="{active:$state.includes('dashboard.menu2')}"><a ui-sref=".menu2">Menu 2</a></li>
<li ng-class="{active:$state.includes('dashboard.menu3')}"><a ui-sref=".menu3">Menu 3</a></li>

BUT: this feature would be in a next ui-router release as we can see here:

cite

To limit activation to target state use new ui-sref-active-eq directive

Breaking Change: Since ui-sref-active now activates even when child states are active you may need to swap out your ui-sref-active with ui-sref-active-eq, thought typically we think devs want the auto inheritance.

Related Topic