Evan Evan - 1 year ago 85
AngularJS Question

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

Is there a way to use

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


app.controller('MainCtrl', function($scope) {
$scope.items = [
color: 'red',
shipping: 2,
color: 'blue',
shipping: 0,
color: 'green',


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

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

Answer Source

Try this: