Syntax
angular.isDefined(value);
The .isDefined() function takes a value to check and returns true or false. Remember, the function is case sensitive.
Let’s now apply this function to first check and variable inside the $scope.
<div ng-app="myApp" ng-controller="myController"></div>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope', function ($val) {
var name = 'Arun Banik';
if (angular.isDefined(name)) {
console.log(name);
}
else
console.log('name is undefined');
} ]
);
</script>
In the above script, I have declared a variable called name and have assigned a value. Later, I am checking if I have defined any value to the variable, using angular.isDefined() function. The output in this case would be the value Arun Banik written to the console.
👉 How to push new elements inside an ngRepeat array from AngularJS $scope
Now, remove the value from the variable name to check the result. In this case, you will see the second message written to the console, that is, name is undefined.
Let us now see another example, where I’ll have an Input box and a button control in the view. While I click the button to submit the value inside the input box, I wish to check if the input box (or textbox) has some value or text defined in it.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myController"> <div> <input type="text" ng-model="name" placeholder="Enter your name" /> <p><button ng-click="submit()">Submit</button></p> </div> <p>{{result}}</p> </div> </body> <script> var myApp = angular.module('myApp', []); myApp.controller('myController', ['$scope', function ($val) { $val.submit = function () { if (angular.isDefined($val.name)) $val.result = 'Hello ' + $val.name + '!'; else $val.result = 'Please enter your name'; } } ] ); </script> </html>
See this demo 👇
{{result}}
👉 If you are new to AngularJS you should know these AngularJS features.
Simple isn’t it. Well, now we know how to prevent or capture the undefined error while submitting values in AngularJS. You can apply this function to check multiple variables or references in your application.
By the way, AngularJS provides another inbuilt function from its “ng” module collection called the angular.isUndefined(). Use this method to do the reverse of I have shown in the above examples, that is, check when a value or reference is undefined. It too returns a Boolean true or false.
Syntax
angular.isUndefined(value);
👉 Before you leave take a look at these AngularJS Filters with example