Angularjs if-then-else 在表达式中的构造 [英] Angularjs if-then-else construction in expression
问题描述
我可以在 angularjs 表达式中以某种方式使用 if-then-else 构造(三元运算符)吗,例如我有函数 $scope.isExists(item) 必须返回 bool 值.我想要这样的东西,
<div>{{item.description}}</div><div>{{isExists(item) ?'可用' : '哦不,你没有它'}}</div>
我知道我可以使用返回字符串的函数,我对在表达式中使用 if-then-else 构造的可能性很感兴趣.谢谢.
Angular 表达式在 1.1.5 之前不支持三元运算符,但可以像这样模拟:
条件 &&(如果为真则回答) ||(如果为假则回答)
所以在示例中,这样的事情会起作用:
<div>{{item.description}}</div><div>{{isExists(item) &&'可用' ||'哦不,你没有它'}}</div>
更新: Angular 1.1.5 添加了对三元运算符的支持:
{{myVar === "二" ?这是真的":这是假的"}}
Can I somehow use if-then-else construction (ternary-operator) in angularjs expression, for example I have function $scope.isExists(item) that has to return bool value. I want something like this,
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div>{{isExists(item) ? 'available' : 'oh no, you don't have it'}}</div>
</div>
I know that I can use function that returns string, I'm interesting in possibility of using if-then-else construction into expression. Thanks.
Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:
condition && (answer if true) || (answer if false)
So in example, something like this would work:
<div ng-repeater="item in items">
<div>{{item.description}}</div>
<div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div>
</div>
UPDATE: Angular 1.1.5 added support for ternary operators:
{{myVar === "two" ? "it's true" : "it's false"}}
这篇关于Angularjs if-then-else 在表达式中的构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!