AngularJS ngClass 条件 [英] AngularJS ngClass conditional

查看:21
本文介绍了AngularJS ngClass 条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以为ng-class 成为条件?

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>

此代码的问题在于,无论 obj.value1 是什么,类测试始终应用于元素.这样做:

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>

只要 obj.value2 不等于真值,就不会应用该类.现在我可以通过执行以下操作来解决第一个示例中的问题:

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>

checkValue1 函数如下所示:

$scope.checkValue1 = function() {
  return $scope.obj.value === 'somevalue';
}

我只是想知道 ng-class 是否应该这样工作.我也在构建一个自定义指令,我想做类似的事情.但是,我找不到观看表达式的方法(也许这是不可能的,这也是为什么它会像这样工作).

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).

这是一个 plnkr 来说明我的意思.

Here is a plnkr to show what I mean.

推荐答案

你的第一次尝试几乎是正确的,它应该可以在没有引号的情况下工作.

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

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

这是一个 plnkr.

ngClass 指令将适用于任何计算为真或假的表达式,有点类似于 Javascript 表达式,但有一些不同,你可以阅读 这里.如果您的条件过于复杂,那么您可以使用返回真值或假值的函数,就像您在第三次尝试中所做的那样.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆