How to use ng-if to test if a variable is defined

Angularjs

Angularjs Problem Overview


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

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:

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>

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

Angularjs Solutions


Solution 1 - Angularjs

Try this:

item.shipping!==undefined

Solution 2 - Angularjs

I edited your plunker to include ABOS's solution.

<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>

plunkerFork

Solution 3 - Angularjs

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEvanView Question on Stackoverflow
Solution 1 - AngularjsABOSView Answer on Stackoverflow
Solution 2 - AngularjsChristoph HegemannView Answer on Stackoverflow
Solution 3 - AngularjsNiko BellicView Answer on Stackoverflow