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);
});
};
You can always add it exactly for your application
@STEVER's answer is satisfactory. However, I thought it may be useful to post a slightly different approach. I use a method called isValue which returns true for all values except null, undefined, NaN, and Infinity. Lumping in NaN with null and undefined is the real benefit of the function for me. Lumping Infinity in with null and undefined is more debatable, but frankly not that interesting for my code because I practically never use Infinity.
The following code is inspired by Y.Lang.isValue. Here is the source for Y.Lang.isValue.
Or as part of a factory
I asked the same question of the lodash maintainers a while back and they replied by mentioning the
!=
operator can be used here:This uses JavaScript's type coercion to check the value for
undefined
ornull
.If you are using JSHint to lint your code, add the following comment blocks to tell it that you know what you are doing - most of the time
!=
is considered bad.Why not simply use
angular.isObject
with negation? e.g.My suggestion to you is to write your own utility service. You can include the service in each controller or create a parent controller, assign the utility service to your scope and then every child controller will inherit this without you having to include it.
Example: http://plnkr.co/edit/NI7V9cLkQmEtWO36CPXy?p=preview
Or you could add it to the rootScope as well. Just a few options for extending angular with your own utility functions.
lodash provides a shorthand method to check if undefined or null:
_.isNil(yourVariable)