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,您的两个选择是:)
-
(condition && result_if_true || !condition && result_if_false)
-
{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采用必须评估为以下之一的表达式:)
- a string of space-delimited class names
(一串以空格分隔的类名)
- an array of class names
(一组类名)
- 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>