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?
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
The reason it didn't work was because, as @charlietfl pointed out, $state was not in scope. So I added the following to my state's controller:
$rootScope.$state = $state;
and it worked great. This plunker is a working example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With