AngularJS 模板中的三元运算符 [英] Ternary operator in AngularJS templates

查看:25
本文介绍了AngularJS 模板中的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何使用 AngularJS 进行三元化(在模板中)?

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

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

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

推荐答案

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

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

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

<小时>

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


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

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

上面的第 2 项创建了一个具有两个属性的对象.数组语法用于选择名称为 true 的属性或名称为 false 的属性,并返回关联的值.

item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.

例如,

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

$first 在第一个元素的 ng-repeat 中设置为 true,因此上述内容仅在第一次通过循环时应用类 'myClass1' 和 'myClass2'.

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

使用 ng-class 有一种更简单的方法:ng-class 采用一个表达式,该表达式必须计算为以下之一:

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

  1. 一串空格分隔的类名
  2. 类名数组
  3. 类名到布尔值的映射/对象.

上面给出了 1) 的示例.这是 3 的示例,我认为它读起来要好得多:

An example of 1) was given above. Here is an example of 3, which I think reads much better:

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

第一次通过 ng-repeat 循环,添加了类 myClass.第三次通过($index 从 0 开始),添加了 anotherClass 类.

The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.

ng-style 采用一个表达式,该表达式必须计算为 CSS 样式名称到 CSS 值的映射/对象.例如,

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

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

这篇关于AngularJS 模板中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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