Search code examples
angularjsstateng-class

Angular - ng-class based on state


Any specific reason why my code is not working?

<li ng-class="{active : $state.includes('products')}">

router code:

.state('products', {
  url: '/products',
  templateUrl: 'app/components/views/products/products.html',
  controller: 'productsController',
  controllerAs: 'products'
})

Solution

  • You are forgetting to set the $state and $stateParams on your $rootScope, if you do so, you can keep using your first approach on html:

    angular.module("myApp").run(function ($rootScope, $state, $stateParams) {
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
    });
    

    This way you don't need to inject them on every single controller.

    Here is the reference: https://github.com/angular-ui/ui-router/wiki/quick-reference#note-about-using-state-within-a-template

    PS: I personally don't recommend this kind of global approach, but it has its merits