Conditionally set Angular's ng-class based on state

tronman picture tronman · Jul 15, 2014 · Viewed 15.1k times · Source

I would like to conditionally set the class of an element based on the application state (using AngularUI Router). I've tried this, but it is not working:

<li ng-class="{active: $state.current.name === 'state1'}">State 1</li>
<li ng-class="{active: $state.current.name === 'state2'}">State 2</li>

Any ideas?

Answer

craigb picture craigb · Jul 24, 2014

You could also use the ui-sref-active directive.

to add the class active to your element when the ui-router state matches use

ui-sref-active="active"

see: http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref-active