AngularJS ngClass conditional
Asked 07 September, 2021
Viewed 1.8K times
  • 60
Votes

Is there any way to make an expression for something like ng-class to be a conditional?

For example, I have tried the following:

<span ng-class="{test: 'obj.value1 == 'someothervalue''}">test</span>

The issue with this code is that no matter what obj.value1 is, the class test is always applied to the element. Doing this:

<span ng-class="{test: obj.value2}">test</span>

As long as obj.value2 does not equal a truthy value, the class in not applied. Now I can work around the issue in the first example by doing this:

<span ng-class="{test: checkValue1()}">test</span>

Where the checkValue1 function looks like this:

$scope.checkValue1 = function() {
  return $scope.obj.value === 'somevalue';
}

I am just wondering if this is how ng-class is supposed to work. I am also building a custom directive where I would like to do something similar to this. However, I can't find a way to watch an expression (and maybe that is impossible and the reason why it works like this).

Here is a plnkr to show what I mean.

11 Answer