Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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

like image 295
Evan Avatar asked Sep 05 '14 21:09

Evan


People also ask

What is the use of NG-if?

Definition and Usage The ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.

How do I know if ngIf is undefined?

How to check if a variable string is empty or undefine or null in Angular. In template HTML component: We can use the ngIf directive to check empty null or undefined. In this example, if stringValue is empty or null, or undefined, It prints the empty message.


2 Answers

Try this:

item.shipping!==undefined 
like image 120
ABOS Avatar answered Sep 20 '22 22:09

ABOS


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

like image 25
Christoph Hegemann Avatar answered Sep 22 '22 22:09

Christoph Hegemann