2016-03-03 50 views
2

我有以下对象名单:如何在AngularJS模板中有条件地显示跨度?

[ 
    { "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

回答

1
<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> 
+0

感谢您的回答;这对我来说是正确的。 –

2

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

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

感谢您的回答。 'ng-if'指令对我来说不起作用,虽然'ng-show'确实如此。我正在使用AngularJS 1.4.7。 –

+0

@AlexReynolds'ng-if'也应该可以工作......'ng-if' /'ng-show'两者都是相似的,但不同的是,'ng-show'根据表达式应用'display:none' css,&'ng -if'会根据表达式值添加删除该元素。 –

1

只要使用它,而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> 
0

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