AngularJS ngClass条件 [英] AngularJS ngClass conditional
问题描述
有没有什么办法让一个前pression这样的事情ngClass是有条件的。例如,我曾尝试以下内容:
<跨度纳克级={测试:'obj.value1 == \\'someothervalue \\''}>测试与LT; / SPAN>
本code的问题是,无论是什么obj.value1,类测试总应用于元素。这样做:
<跨度纳克级={测试:obj.value2}>测试与LT; / SPAN>
只要在不施加obj.value2不等于一个truthy值的类。现在,我可以做这个解决此问题在第一个例子:
<跨度纳克级={测试:checkValue1()}>测试与LT; / SPAN>
其中checkValue1功能如下:
$ scope.checkValue1 =功能(){
返回$ scope.obj.value ==='someValue中;
}
我只是想知道,如果这是ngClass是如何工作的。我也建立一个自定义的指令,我愿做一些类似的。不过,我不能找到一种方法来观看一个前pression(也许这是不可能的,为什么它的工作原理是这样的原因)。
下面是一个plnkr表明我的意思:
<一个href=\"http://plnkr.co/edit/iSh0t8swDEyGbh7ylZg2?p=$p$pview\">http://plnkr.co/edit/iSh0t8swDEyGbh7ylZg2?p=$p$pview
您的第一次尝试是差不多吧,它应该不带引号。
{测试:obj.value1 =='someothervalue'}
下面是一个 plnkr 。
该ngClass指令将由该评估truthy或falsey,类似的JavaScript前pressions但有一些差异的任何一点前pression工作,你可以阅读有关的此处。
如果你的条件太复杂,那么你可以使用返回truthy或falsey功能,正如你在第三次尝试一样。</ P>
只是补充:您还可以使用逻辑运算符形成逻辑EX pressions像
纳克级={'测试':obj.value1 =='someothervalue'|| obj.value2 =='somethingelse'}
Is there any way to make an expression for something like ngClass 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 ngClass 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:
http://plnkr.co/edit/iSh0t8swDEyGbh7ylZg2?p=preview
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'}"
这篇关于AngularJS ngClass条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!