0 votes
1 view
in Web Technology by (47.8k points)

Is there any way to make an expression for something like ng-class to be 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 is 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.

1 Answer

0 votes
by (107k points)

The first thing you have done is almost right, the only thing you need to remove is quotes and it will work.

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

You can also use logical operators to form logical expressions like as follows:-

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

Related questions

+2 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
0 answers
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...