Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

html - AngularJS ngClass条件(AngularJS ngClass conditional)

Is there any way to make an expression for something like ng-class to be a conditional?

(有什么办法可以使像ng-class这样的表达式成为条件表达式吗?)

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.

(此代码的问题在于,无论obj.value1是什么,类测试始终应用于该元素。)

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.

(只要obj.value2不等于真实值,就不会应用该类。)

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:

(其中checkValue1函数如下所示:)

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

I am just wondering if this is how ng-class is supposed to work.

(我只是想知道ng-class是否应该工作。)

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.

(这是显示我的意思的plnkr 。)

  ask by ryanzec translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(您的第一次尝试几乎是正确的,它应该没有引号。)

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

Here is a plnkr .

(这是一个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 .

(ngClass指令可与任何评估为真或假的表达式一起使用,这有点类似于Javascript表达式,但有一些区别,您可以在这里阅读。)

If your conditional is too complex, then you can use a function that returns truthy or falsey, as you did in your third attempt.

(如果条件太复杂,则可以像第三次尝试一样使用返回true或false的函数。)

Just to complement: You can also use logical operators to form logical expressions like

(只是为了补充:您还可以使用逻辑运算符来形成逻辑表达式,例如)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...