How to check if a scope variable is undefined in AngularJS template?
Solution 1:
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!
Solution 2:
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>
Solution 3:
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/