Era Era - 1 year ago 58
AngularJS Question

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'

Answer Source

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:

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