如何在值为空时隐藏标签文本?

时间:2013-09-24 23:07:13

标签: angularjs

在表格单元格中,我列出了几个使用ng-repeat填充的项目,使用下面的结构。但是,对于某些条目,“user.favcolor”等属性为空。在这种情况下隐藏文本的最简单方法是什么,例如“喜欢的颜色:”,这样我最终不会有一个“喜欢的颜色:”并且旁边没有值的行?

        <table>
            <thead>
                <tr>
                    <th>Price</th>
                    <th>Plan Contents</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="tip in tips">
                    <td>{{tip.priceMonthly}}</td>
                    <td><span>Name: {{user.name}}</span>
                        <span>ID: {{user.id}}</span>
                        <span>Favorite color: {{user.favcolor}}</span>
                    </td>
                </tr>
            </tbody>
        </table>

1 个答案:

答案 0 :(得分:36)

您可以使用ng-show指令:

<span ng-show="user.favcolor">Favorite color: {{user.favcolor}}</span>

ng-show的作用是仅在表达式求值为true时才显示该元素。这里的空字符串将评估为隐藏整个元素的false

或者,您也可以指定默认值:

<span>Favorite color: {{user.favcolor || "Not specified" }}</span>

在这种情况下,如果user.favcolor评估为false,则会改为打印Not specified

相关问题