How to determine if the variable is undefined or null in AngularJS?

How to determine if the variable is undefined or null? Angular have angular.isUndefined but not angular.isUndefinedOrNull. In this post, we will show 3 ways to determine if the var is undefined or null.

  • You can always solve this by using below function:

angular.isUndefinedOrNull = function(val) {

return angular.isUndefined(val) || val === null

}

angular.isUndefined(val) is true if undefined.

  • Another alternative is to write the utility service that can be included in each controller or create one parent controller and assign the utility service to your scope and then every child controller will inherit this without you having to include it.

Below is the AngularJS controller and service:


var app = angular.module('youvcode', []);

app.controller('MainCtrl', function($scope, Utils) {
$scope.utils = Utils;
});

app.controller('ChildCtrl', function($scope, Utils) {
$scope.undefined1 = Utils.isUndefinedOrNull("youvcode.com");
$scope.undefined2 = $scope.utils.isUndefinedOrNull(45);
$scope.undefined3 = $scope.utils.isUndefinedOrNull();

});

app.factory('Utils', function() {
var service = {
isUndefinedOrNull: function(obj) {
return angular.isDefined(obj) || obj===null;
}
}
return service;
});

Example: https://jsfiddle.net/Lt7aP/5653/

  • The third option is to use angular.isObject with negation as shown below:

if (!angular.isObject(obj)) {

return;

}

isObject returns true if value is an object but not null. Also it does not work for primitive types.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s