【问题标题】:How to conditionally show span in AngularJS template?如何在 AngularJS 模板中有条件地显示跨度?
【发布时间】:2016-06-17 10:19:29
【问题描述】:

我有以下对象列表:

[
    { "name" : "foo", "description" : "description of foo..." },
    { "name" : "bar", "description" : "description of bar..." },
    { "name" : "baz" },
    ...
]

所有对象都有一个name,但有些有一个关联的description,其余的没有。

我使用以下模板和一个连接到预先输入的 input 字段来显示每个匹配的对象:

<script type="text/ng-template" id="my-template.html">
    <a style="text-align: left;">
        <span style="font-size: 18px; display:block;">{{match.model.name}}</span> 
        <span ng-show="typeof({{match.model.description}}) !== 'undefined'">{{match.model.description}}</span>
    </a>
</script>

我希望模板仅在定义其值时显示description,但我使用ng-show 会返回解析错误。

我应该如何使用ng-show 或其他指令来呈现description,仅当此对象键(及其值)可用时?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    你应该只检查变量值,这就足够了

    <span ng-if="match.model.description">{{match.model.description}}</span>
    

    【讨论】:

    • 感谢您的回答。 ng-if 指令对我不起作用,尽管 ng-show 可以。我正在使用 AngularJS 1.4.7。
    • @AlexReynolds ng-if 也应该工作.. ng-if/ng-show 两者相似,但不同,ng-show 适用 display:none 基于表达式的 css,& ng-if 确实添加根据表达式值删除该元素。
    【解决方案2】:
    <script type="text/ng-template" id="my-template.html">
        <a style="text-align: left;">
            <span style="font-size: 18px; display:block;">{{match.model.name}}</span> 
            <span ng-show="match.model.description">{{match.model.description}}</span>
        </a>
    </script>
    

    【讨论】:

    • 感谢您的回答;这对我来说是正确的。
    【解决方案3】:

    只需在没有typeof 的情况下使用它 - 并且不要使用大括号,因为ng-show 已经与您的范围相关。在 JavaScript 中,if(undefined)if(false) 具有相同的结果(参见Undefined variables, value == false versus !value

    <script type="text/ng-template" id="my-template.html">
      <a style="text-align: left;">
        <span style="font-size: 18px; display:block;">{{match.model.name}}</span> 
        <span ng-show="match.model.description">{{match.model.description}} </span>
      </a>
    </script>
    

    【讨论】:

      【解决方案4】:

      使用ng-if="match.model.description" 而不是ng-show。 ngIf 与 ngShow 的不同之处在于 ngIf 完全删除并重新创建 DOM 中的元素,而不是通过 display css 属性更改其可见性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多