AngularJS ngClass条件(AngularJS ngClass conditional)

编程入门 行业动态 更新时间:2024-10-24 20:13:40
AngularJS ngClass条件(AngularJS ngClass conditional)

有没有办法使像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'}"

更多推荐

本文发布于:2023-07-09 02:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1082886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   AngularJS   ngClass   conditional

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!