【问题标题】:Angular ternary operators角度三元运算符
【发布时间】:2015-05-03 07:17:17
【问题描述】:

我正在尝试使用三元运算符来设置我的模板的一部分:

account.accountType === "" ? "" : "Type: " + account.accountType

此代码 sn-p 如果为空,则应省略类型标签。但是,类型标签始终存在:

评估为真:Type:
评估为假:Type: {{ account.accountType }}

我想要的行为是:

评估为真:""
评估为假:Type: {{ account.accountType }}

这是角度三元运算符的缺点,还是我的代码中的错误?谢谢!

【问题讨论】:

    标签: angularjs ternary-operator


    【解决方案1】:

    ""null 不同。

    我建议你利用null""等的“虚假”行为,做如下操作:

    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 &amp;&amp; "Type: " + account.accountType
    • @gustavohenke 是的。谢谢。
    • 有没有办法在“类型:”条件中包含 HTML 标记?
    • @mattchue 我不知道。如果您想在视图中操作 HTML,有比尝试使用条件运算符更好的方法(请参阅我的编辑)。
    猜你喜欢
    • 2020-07-16
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多