如何使用ng-if测试变量是否已定义 [英] How to use ng-if to test if a variable is defined

查看:162
本文介绍了如何使用ng-if测试变量是否已定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使用ng-if来测试是否定义了一个变量,而不仅仅是它是否真实?

Is there a way to use ng-if to test if a variable is defined, not just if it's truthy?

在下面的示例中(实时演示),HTML仅显示红色商品的运费,因为item.shipping既定义又非零.我还想显示蓝色项目的费用(已定义装运,但为零),而不显示绿色项目的费用(未定义装运).

In the example below (live demo), the HTML displays a shipping cost for the red item only, because item.shipping is both defined and nonzero. I'd like to also display a cost for the blue item (shipping defined but zero), but not for the green item (shipping not defined).

JavaScript:

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'也没有.

I tried doing ng-if='angular.isDefined(item.shipping)', but it didn't work. Nor did ng-if='typeof(item.shipping) !== undefined'.

推荐答案

尝试一下:

item.shipping!==undefined

这篇关于如何使用ng-if测试变量是否已定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆