有没有办法使用ng-if
来测试变量是否定义,而不仅仅是它的真实性?
在下面的示例中(live demo),HTML仅显示红色项目的运费,因为item.shipping
已定义且非零。我还想显示蓝色商品的费用(已定义运费但为零),但不是绿色商品的费用(未定义运费)。
JavaScript的:
app.controller('MainCtrl', function($scope) {
$scope.items = [
{
color: 'red',
shipping: 2,
},
{
color: 'blue',
shipping: 0,
},
{
color: 'green',
}
];
});
HTML:
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
我尝试过ng-if='angular.isDefined(item.shipping)'
,但它没有用。也没有ng-if='typeof(item.shipping) !== undefined'
。
答案 0 :(得分:88)
试试这个:
item.shipping!==undefined
答案 1 :(得分:10)
我编辑了你的plunker以包含ABOS的解决方案。
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
答案 2 :(得分:4)
您仍然可以使用 angular.isDefined()
你只需要设置
$rootScope.angular = angular;
在&#34; run&#34;相。
请参阅update plunkr:http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview