有没有办法使像ngClass这样的表达式成为有条件的。 例如,我尝试过以下操作:
<span ng-class="{test: 'obj.value1 == \'someothervalue\''}">test</span>这个代码的问题是,无论什么obj.value1,类测试总是应用于元素。 这样做:
<span ng-class="{test: obj.value2}">test</span>只要obj.value2不等于真值,该类就没有应用。 现在我可以在第一个例子中解决这个问题:
<span ng-class="{test: checkValue1()}">test</span>checkValue1功能如下所示:
$scope.checkValue1 = function() { return $scope.obj.value === 'somevalue'; }我只是想知道ngClass应该如何工作。 我也在构建一个自定义的指令,我想做一些类似的操作。 然而,我找不到一种方式来观看表达式(也许这是不可能的,为什么它的工作原理如此)。
这是一个plnkr来显示我的意思:
http://plnkr.co/edit/iSh0t8swDEyGbh7ylZg2?p=preview
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.
最满意答案
你的第一个尝试几乎是正确的,它应该没有引号。
{test: obj.value1 == 'someothervalue'}这是一个plnkr 。
ngClass指令将使用任何表达式来评估真实或虚假,与Javascript表达式有点类似,但有一些区别,您可以在这里阅读。 如果您的条件太复杂,那么您可以使用返回真实或虚假的函数,就像您在第三次尝试中所做的那样。
只是补充:您也可以使用逻辑运算符来形成逻辑表达式,如
ng-class="{'test': obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}"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'}"更多推荐
发布评论