Activating classes using ng-class and $state.is, $state.includes
In the ui-router sample, it's shown that one can apply certain CSS classes depending on the current state using ng-class (src)
<ul class="nav">
<!-- Here you can see ui-sref in action again. Also notice the use of $state.includes, which
will set the links to 'active' if, for example on the first link, 'contacts' or any of
its descendant states are activated. -->
<li ng-class="{ active: $state.includes('contacts') }"><a ui-sref="contacts.list">Contacts</a></li>
<li ng-class="{ active: $state.includes('about') }"><a ui-sref="about">About</a></li>
</ul>
However, I've tried to do the same in my application, but I'm not seeing the class activating. Plunker example here.
<ul class="nav">
<li ng-class="{active: $state.is('route1')}"><a ui-sref="route1">Route 1</a></li>
<li ng-class="{active: $state.includes('route2')}"><a ui-sref="route2">Route 2</a></li>
<li ng-class="{active: $state.includes('route3')}"><a ui-sref="route3">Route 3</a></li>
<li><a ui-sref="#">Route 4</a></li>
</ul>
Can someone shed some light as to why this might be? Is the $state service not available for some reason? Thanks in advance.
You have to expose $state in the scope to make $state accessible in expressions.
In the sample it is done here.
Very true. Thanks for the tip.
The link to the sample is down so here is a plunk: http://plnkr.co/edit/dDCcan?p=preview
You can use ui-sref-active
<ul class="nav">
<li ui-sref-active="active"><a ui-sref="route1">Route 1</a></li>
<li ui-sref-active="active"><a ui-sref="route2">Route 2</a></li>
<li ui-sref-active="active"><a ui-sref="route3">Route 3</a></li>
<li><a ui-sref="#">Route 4</a></li>
</ul>"
But with ui-sref-active, your list item becomes a link. What if you don't want that ?
It's the that makes it a link
angular.module('myApp', ['ui.router'])
.run(['$rootScope', '$state', function ($rootScope, $state) {
$rootScope.$state = $state;
}]);
This will work and also will be available to get to any child of any navbar Then you can use:
ng-class="{activeState: $state.includes('state1') || $state.includes('state2')}"
if I want to use it in a loop what should I do to declare a state includes?
<li ng-repeat="(name,item) in adminMenu" ng-class="{active: $state.includes(item.tag)}">
{active: $state.includes(item.tag)} or {active: $state.includes({{item.tag}})} or {active: $state.includes('item.tag')}
The first one is the correct.
What if the route has some params {activated:$state.includes('app.resident_service({fold:\'valet\'})')