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

How to check if a scope variable is undefined?

This does not work:

<p ng-show="foo == undefined">Show this if $scope.foo == undefined</p> 
+53
angularjs angularjs-ng-show
Nov 20 '14 at 15:00
source share
9 answers

Here is the cleanest way to do this:

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

No need to create an auxiliary function in the controller!

+65
May 02 '15 at 20:52
source share

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

However, to answer your question: I think the best way to do this is to add a helper function.

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

and in the template

 <div ng-show="isUndefined(foo)"></div> 
+24
Nov 20 '14 at 15:11
source share

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/

+9
Nov 20 '14 at 15:02
source share

If foo not a boolean variable then this will work (i.e. you want to show this when this variable has some data):

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

And vice versa:

<p ng-show="foo">Show this if $scope.foo is defined</p>

+3
Dec 05 '16 at 0:06
source share

Submitting a new response since the behavior of Angular has changed. Equality checking with undefined now works in Angular expressions with at least 1.5, as the following code works:

 ng-if="foo !== undefined" 

If ng-if is true, removing the percentages property from the corresponding area and calling $ digest removes the item from the document, as you would expect.

+3
Mar 20 '17 at 21:23
source share

If you are using Angular 1, I would recommend using the built-in Angular method:

angular.isDefined (value);

link: https://docs.angularjs.org/api/ng/function/angular.isDefined

+1
Mar 20 '17 at 11:01
source share

You can use the double pipe operation to check if a value is undefined after the statement:

 <div ng-show="foo || false"> Show this if foo is defined! </div> <div ng-show="boo || true"> Show this if boo is undefined! </div> 

Check JSFiddle on demo

For a technical explanation of the double pipe, I prefer to take a look at this link: https://stackoverflow.com/a/4646/

+1
Feb 18 '18 at 8:14
source share

As @impulsgraw wrote. You need to check the uncertainty after the channels:

 <div ng-show="foo || undefined"> Show this if foo is defined! </div> <div ng-show="boo || !undefined"> Show this if boo is undefined! </div> 

https://jsfiddle.net/mjfz2q9h/11/

0
Jun 05 '19 at 13:23
source share

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

-2
May 20 '15 at 18:25
source share



All Articles