Daniel
Daniel

Reputation: 1755

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' : ''"

Upvotes: 0

Views: 429

Answers (1)

Mistalis
Mistalis

Reputation: 18309

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' : ''"

Upvotes: 1

Related Questions