Sometimes I need to check a value for three conditions at the same time, null, undefined or "". Due that I haven´t found any method to do this, I coded my own and it works.
$scope.isNullOrEmptyOrUndefined = function (value) {
if (value === "" || value === null || typeof value === "undefined") {
return true;
}
}
Just wanted to know if there is a better way to accomplish the same thing.
Thanks so much in advance,
Guillermo
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. Return Value: It returns true if the value passed is undefined else returns false.
The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator. Note: We cannot use the typeof operator for null as it returns object .
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.
How about this? Since you seem to be returning true in those null/undefined cases:
$scope.isNullOrEmptyOrUndefined = function (value) {
return !value;
}
http://jsfiddle.net/1feLd9yn/3/
Note that an empty array and empty object will also return false as they are truthy values. If you want the true/false return to be flip-flopped, then omit the ! before value.
As mentioned in the comments it's better to use return !value
.
$scope.isValid = function(value) {
return !value
}
A proper way is simply to use angular.isDefined()
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