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
386 views
in Technique[技术] by (71.8m points)

javascript - AngularJS模板中的三元运算符(Ternary operator in AngularJS templates)

How do you do a ternary with AngularJS (in the templates)?

(你如何使用AngularJS三元组(在模板中)?)

It would be nice to use some in html attributes (classes and style) instead of creating and calling a function of the controller.

(在html属性(类和样式)中使用一些而不是创建和调用控制器的函数会很好。)

  ask by cricardol translate from so

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

1 Reply

0 votes
by (71.8m points)

Update : Angular 1.1.5 added a ternary operator , so now we can simply write

(更新 :Angular 1.1.5增加了一个三元运算符 ,所以现在我们可以简单地写一下)

<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">

If you are using an earlier version of Angular, your two choices are:

(如果您使用的是早期版本的Angular,您的两个选择是:)

  1. (condition && result_if_true || !condition && result_if_false)
  2. {true: 'result_if_true', false: 'result_if_false'}[condition]

item 2. above creates an object with two properties.

(上面的第2项创建了一个具有两个属性的对象)

The array syntax is used to select either the property with name true or the property with name false, and return the associated value.

(数组语法用于选择名称为true的属性或名称为false的属性,并返回关联的值。)

Eg,

(例如,)

<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
 or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>

$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.

(对于第一个元素,$ first在ng-repeat内设置为true,因此上面只会在第一次循环时应用类'myClass1'和'myClass2'。)

With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following:

(使用ng-class时,有一种更简单的方法:ng-class采用必须评估为以下之一的表达式:)

  1. a string of space-delimited class names

    (一串以空格分隔的类名)

  2. an array of class names

    (一组类名)

  3. a map/object of class names to boolean values.

    (类名的映射/对象为布尔值。)

An example of 1) was given above.

(上面给出了1)的一个例子。)

Here is an example of 3, which I think reads much better:

(这是一个3的例子,我认为它读得更好:)

 <li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>

The first time through an ng-repeat loop, class myClass is added.

(第一次通过ng-repeat循环,添加了类myClass。)

The 3rd time through ($index starts at 0), class anotherClass is added.

(第3次通过($ index从0开始),添加了class anotherClass。)

ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values.

(ng-style采用必须将CSS样式名称的地图/对象评估为CSS值的表达式。)

Eg,

(例如,)

 <li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>

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

...