AngularJS - Filter empty objects

早过忘川 提交于 2019-11-27 08:23:19

We can simply use ng-if here:

<div ng-repeat="data in myData " ng-if="data.Message">
 {{ data.ID }}
 {{ data.Message }}
</div>

You can use a function instead of an object like this

<div ng-repeat="data in myData | filter:emptyOrNull">
  {{ data.ID }}
  {{ data.Message }}
</div>

And in the controller

$scope.emptyOrNull = function(item){
  return !(item.Message === null || item.Message.trim().length === 0)
}

Well you can create a custom filter:

.filter('hasSomeValue', [function(){
    return function(input, param) {
        var ret = [];
        if(!angular.isDefined(param)) param = true;

        angular.forEach(input, function(v){
            if(angular.isDefined(v.Message) && v.Message) {
                v.Message = v.Message.replace(/^\s*/g, '');
                ret.push(v);
            }
        });

        return ret;
    };
}])

And in your HTML:

<div ng-repeat="data in myData | hasSomeValue: data.Message">

DEMO

You can use '' charter. Try check like this.

<div ng-repeat="data in myData | filter:{Message: ''}">

You can use an angular filter for this:

Working Fiddle

Code Snippet:

.filter('filterData',function(){
    return function(data) {
        var dataToBePushed = [];
        data.forEach(function(resultData){
            if(resultData.Message && resultData.Message != " ")
                dataToBePushed.push(resultData);
        });
        return dataToBePushed;
    }
});

If you wanted to filter out values in an object that are empty, you could create a custom filter and filter each based on the value.

Something like this:

.filter("notEmpty",
function () {
    return function (object) {
        var filteredObj = {};
        angular.forEach(object, function (val, key) {
            if (val != null) {
                if (typeof(val) === "object") {
                    if (Object.keys(val).length > 0) {
                        filteredObj[key] = val;
                    }
                } else if (typeof(val) === "string") {
                    if (val.trim() !== "") {
                        filteredObj[key] = val;
                    }
                } else {
                    filteredObj[key] = val;
                }
            }
        });
        return filteredObj;
    };
});

jsFiddle example

You could also use the ng-if directive and a function that parses the objects as you see fit.

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