When I write watch handling functions I check newVal param on undefined
and null
. Why does AngularJS have such a behavior, but doesn't have particular utility method? So there is angular.isUndefined
but not angular.isUndefinedOrNull
. It isn't hard to implement that by hand but how extend angular to have that function in each controller? Tnx.
Edit:
The example:
$scope.$watch("model", function(newVal) { if (angular.isUndefined(newVal) || newVal == null) return; // do somethings with newVal }
Is it common accepted practice to handle such a way?
Edit 2:
The JSFiddle example (http://jsfiddle.net/ubA9r/):
<div ng-app="App"> <div ng-controller="MainCtrl"> <select ng-model="model" ng-options="m for m in models"> <option value="" class="ng-binding">Choose model</option> </select> {{model}} </div> </div> var app = angular.module("App", []); var MainCtrl = function($scope) { $scope.models = ['Apple', 'Banana']; $scope.$watch("model", function(newVal) { console.log(newVal); }); };
How to check if a variable string is empty or undefine or null in Angular. In template HTML component: We can use the ngIf directive to check empty null or undefined. In this example, if stringValue is empty or null, or undefined, It prints the empty message.
You can use angular's function called angular. isUndefined(value) returns boolean. Show activity on this post. if(!a) { // do something when `a` is not undefined, null, ''. }
A brief search shows that (in the Angular code base starting from ./packages) assignment to null ( = null, notice the leading space to avoid matching === null) occurs 1448 times, and assignment to undefined ( = undefined) can be found 1905 times.
You can use angular's function called angular.isUndefined (value) returns boolean. You may read more about angular's functions here: AngularJS Functions (isUndefined) if (!a) { // do something when `a` is not undefined, null, ''. } (!value) ?
Typescript component, Written a function for checking null or undefined or empty using typeOf operator It is check for undefined value and returns true if it is null In template html component: We can use ngIf directive to check empty null or undefined.
AngularJS | angular.isUndefined () Function Last Updated : 12 Apr, 2019 The angular.isUndefined () function in AngularJS is used to determine the value inside isUndefined function is undefined or not. It returns true if the reference is undefined otherwise returns false.
You can always add it exactly for your application
angular.isUndefinedOrNull = function(val) { return angular.isUndefined(val) || val === null }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With