How to check if a scope variable is undefined in AngularJS template? How to check if a scope variable is undefined in AngularJS template? angularjs angularjs

How to check if a scope variable is undefined in AngularJS template?


Here is the cleanest way to do this:

<p ng-show="{{foo === undefined}}">Show this if $scope.foo === undefined</p>

No need to create a helper function in the controller!


Using undefined to make a decision is usually a sign of bad design in Javascript. You might consider doing something else.

However, to answer your question: I think the best way of doing so would be adding a helper function.

$scope.isUndefined = function (thing) {    return (typeof thing === "undefined");}

and in the template

<div ng-show="isUndefined(foo)"></div>


Corrected:

HTML

  <p ng-show="getFooUndef(foo)">Show this if $scope.foo === undefined</p>

JS

$scope.foo = undefined;$scope.getFooUndef = function(foo){    return ( typeof foo === 'undefined' );}

Fiddle: http://jsfiddle.net/oakley349/vtcff0w5/1/