HTML 属性中的 AngularJS 条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13780788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:16:19  来源:igfitidea点击:

AngularJS conditionals in HTML Attribute

htmlangularjs

提问by Quang Van

How would you change an htmlattribute based on the model?

您将如何html根据模型更改属性?

I'm trying to change an input's placeholder text based on a length of an array:

我正在尝试根据数组的长度更改输入的占位符文本:

<input placeholder="{{todos.length ? 'Insert todo' : 'Insert your first todo'}}" />

But that doesn't seem to work...

但这似乎不起作用......

JS Bin code example.

JS Bin 代码示例

采纳答案by Ben Brandt

For anyone else who comes across this (like I just did via Google), it looks like Angular recently added support for the ternary operator in expressions. I just used it successfully in 1.2.16 to dynamically update a tooltip (title) attribute. It seems to have first appeared in the documentation for 1.2.17, although they still generally discourage its use:

对于遇到此问题的任何其他人(就像我刚刚通过 Google 所做的那样),看起来 Angular 最近在表达式中添加了对三元运算符的支持。我刚刚在 1.2.16 中成功使用它来动态更新工具提示(标题)属性。它似乎首先出现在 1.2.17 的文档中,尽管他们通常仍然不鼓励使用它:

From: AngularJS: Developer Guide: Expressions

来自:AngularJS:开发人员指南:表达式

Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the Angular philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead.

除了三元运算符 (a ? b : c),您不能在表达式中编写控制流语句。这背后的原因是 Angular 哲学的核心,即应用程序逻辑应该在控制器中,而不是在视图中。如果您需要真正的条件、循环或从视图表达式中抛出,请改为委托给 JavaScript 方法。

回答by jaime

The ternary operator doesn't seem to work in this case, instead of doing this

三元运算符在这种情况下似乎不起作用,而不是这样做

{{cond ? true : false}}

Change it to

将其更改为

{{ exp && true || false }}

So your placeholderattribute would look like this (I have shortened it for demonstration purposes)

所以你的placeholder属性看起来像这样(为了演示目的,我缩短了它)

placeholder="{{todos.length > 0 && 'Insert' || 'Insert first'}}"