在模板中三元 [英] A ternary in templates

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

问题描述

你怎么做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.

推荐答案

更新:角1.1.5增加了的三元运算符,所以现在我们可以简单的写

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

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


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


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


  1. (条件和放大器;&安培; result_if_true ||条件和放大器;!&安培; result_if_false)

  2. {真:result_if_true',假:result_if_false'} [状态]

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

以上项目2.创建一个具有两个属性的对象。该数组语法是用来选择与真实名称属性或名称虚假的财产,并返回相应的值。

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>

$第一个设置为true的NG-重复的第一个元素在里面,所以上述适用阶级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-类获取前pression必须评估下列之一:

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-重复循环,MyClass类添加。通过第三次($指数从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-风格需要一个前pression必须评估为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>

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

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