AngularJS ngClass conditional

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.

1Best Answer
11

Your first attempt was almost right, It should work without the quotes.

{test: obj.value1 == 'someothervalue'}

Here is a plnkr.

The ngClass directive will work with any expression that evaluates truthy or falsey, a bit similar to Javascript expressions but with some differences, you can read about here.
If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.

Just to complement: You can also use logical operators to form logical expressions like

ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"

Leave a Comment