Check if value is not empty and not null in angular template?

落爺英雄遲暮 提交于 2020-12-09 00:44:25

问题


How do I check if value is not empty and not null.

in Controller: $scope.data.variable = 'some valid data';

<div ng-if="data.variable != ''">something else</div>

Thanks


回答1:


since both null and empty are falsy values

div.variable if not null or empty will evaluate to true and if either of null or empty will evaluate to false

 <div ng-if="data.variable">something else</div>



回答2:


I suggest you have such a function is your controller:

$scope.isEmpty = function(value){
return (value == "" || value == null);
};

And your 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.




回答3:


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;

$scope.isValid = function(val) {
    var ret = true;
    if (angular.isString(val)) {
        ret = ret && (val.length > 0);
    }
    return ret && (val !== null);
}


来源:https://stackoverflow.com/questions/27634736/check-if-value-is-not-empty-and-not-null-in-angular-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!