Background
I am creating an application with a menu on the left that contains several menu items. When a user clicks on an element (or accesses it through a URL), I want to highlight the element (that is, Apply the class "active" to the corresponding <li> ).
Note. I process routes using ui.router .
What i tried
So far I am trying to use the ng-class directive:
<div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar"> <li ng-class="{active: current=='container.item1'}"> <a href="#/a/item1">Item 1</a> </li> <li ng-class="{active: current=='container.item2'}"> <a href="#/a/item2">Item 2</a> </li> <li ng-class="{active: current=='container.item3'}"> <a href="#/a/item3">Item 3</a> </li> </ul>
And on the js side:
.controller('container', function($scope, $rootScope, $state) { $rootScope.$on('$stateChangeSuccess', function(){ $scope.current = $state.current.name; } ) })
This works pretty well, but I wondered if it is possible to refer to the state directly in the template, without having to manually handle the event. Sort of:
<ul class="nav nav-sidebar"> <li ng-class="{active: $state.current.name =='container.item1'}"> <a href="#/a/item1">Item 1</a> </li> <li ng-class="{active: $state.current.name =='container.item2'}"> <a href="#/a/item2">Item 2</a> </li>
(which does not work)
Any idea?
source share