Search code examples
angularjsangular-ui-routerng-class

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?


Solution

  • 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.