Angular 三元运算符
Angular ternary operators
我正在尝试使用三元运算符来设置我的模板的一部分:
account.accountType === "" ? "" : "Type: " + account.accountType
如果 Type 标签为 null,此代码片段应省略。但是,类型标签始终存在:
计算结果为真:Type:
计算结果为假:Type: {{ account.accountType }}
我想要的行为是:
计算结果为真:""
计算结果为假:Type: {{ account.accountType }}
这是angular三元运算符的缺点,还是我的代码有错误?谢谢!
""
与 null
不同。
我建议您利用 null
、""
等的行为作为 "falsy" 并执行以下操作:
account.accountType ? "Type: " + account.accountType : ""
甚至(感谢 gustavohenke):
account.accountType && "Type: " + account.accountType
如果你想有条件地在你的视图中包含 HTML,你可能最好使用类似 ng-if
:
的东西
<span ng-if="account.accountType" class=".....">Type: {{ account.accountType }}</span>
我正在尝试使用三元运算符来设置我的模板的一部分:
account.accountType === "" ? "" : "Type: " + account.accountType
如果 Type 标签为 null,此代码片段应省略。但是,类型标签始终存在:
计算结果为真:Type:
计算结果为假:Type: {{ account.accountType }}
我想要的行为是:
计算结果为真:""
计算结果为假:Type: {{ account.accountType }}
这是angular三元运算符的缺点,还是我的代码有错误?谢谢!
""
与 null
不同。
我建议您利用 null
、""
等的行为作为 "falsy" 并执行以下操作:
account.accountType ? "Type: " + account.accountType : ""
甚至(感谢 gustavohenke):
account.accountType && "Type: " + account.accountType
如果你想有条件地在你的视图中包含 HTML,你可能最好使用类似 ng-if
:
<span ng-if="account.accountType" class=".....">Type: {{ account.accountType }}</span>