Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally set Angular's ng-class based on state

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?

like image 694
tronman Avatar asked Jul 15 '14 17:07

tronman


2 Answers

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

like image 75
craigb Avatar answered Oct 14 '22 13:10

craigb


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.

like image 34
tronman Avatar answered Oct 14 '22 14:10

tronman