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

查看:1754
本文介绍了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. (条件&& result_if_true ||!condition&&< result_if_false)

  2. {true:'result_if_true',false:'result_if_false'} [condition]

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

项目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。第3次通过($ index从0开始),添加了class 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 采用必须求值为a的表达式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天全站免登陆