Search code examples
angularjsng-class

How to set ng-class if?


I have array in Angular JS with string values: ["dog", "cat"]

How to set class using directive ng-class where item.type in array?

I mean this case:

ng-class="item.name in filter.categories? 'red' : ''"

Solution

  • Use a function that check if your value is in the array:

    $scope.isAnimal = function(val) {
        for(let i = 0; i < $scope.animals.length; i++) 
            if(val == $scope.animals[i]) return true;
        return false;
    }
    

    Then, you can apply your ng-class from the result of this function:

    ng-class="{'red': isAnimal(item.name)}"
    

    With a ternary operator, it could be:

    ng-class="isAnimal(item.name) ? 'red' : ''"