Javascript 检查角度模板中的值是否不为空且不为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27634736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if value is not empty and not null in angular template?
提问by user3063182
How do I check if value is not empty and not null.
如何检查值是否不为空且不为空。
in Controller:
$scope.data.variable = 'some valid data';
在控制器中:
$scope.data.variable = 'some valid data';
<div ng-if="data.variable != ''">something else</div>
<div ng-if="data.variable != ''">something else</div>
Thanks
谢谢
回答by A.B
since both null and empty are falsy values
因为 null 和 empty 都是假值
div.variable if notnullor emptywill evaluate to trueand if either of nullor emptywill evaluate to false
div.variable 如果notnull或empty将评估为true,如果其中之一null或empty将评估为假
<div ng-if="data.variable">something else</div>
回答by user3063182
I suggest you have such a function is your controller:
我建议你有这样一个功能是你的控制器:
$scope.isEmpty = function(value){
return (value == "" || value == null);
};
And your HTML:
还有你的 HTML:
<div ng-if="!isEmpty(data.variable)">something else</div>
If this function will be useful in many of your pages I suggest you put it on the $rootScope, so that it's recognized in the entire application.
如果此功能在您的许多页面中都有用,我建议您将其放在 $rootScope 上,以便在整个应用程序中都能识别它。
回答by Ashesh
From what it looks like in your case, I think you're expecting either an empty string, or null. To write a reasonable check, I would consider it best to go about it like this;
从您的情况来看,我认为您期望的是一个空字符串,或者null. 为了写出合理的支票,我认为最好这样做;
$scope.isValid = function(val) {
var ret = true;
if (angular.isString(val)) {
ret = ret && (val.length > 0);
}
return ret && (val !== null);
}

