Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Filter empty objects

I have a $scope.myData object that contain a chunk of data. What i am trying to do is display the data but filter out the nulls and empty strings:

$scope.myData = [
    {
       "ID" : "001",
       "Message" : "test test test test"
    },
    {
       "ID" : "002",
       "Message" : "test test test test"
    },
    {
       "ID" : "003",
       "Message" : "test test test test"
    },
    {
       "ID" : "004",
       "Message" : "test test test test"
    },
    {
       "ID" : "005",
       "Message" : " "
    },
    {
       "ID" : "006",
       "Message" : "test test test test"
    },
    {
       "ID" : "007",
       "Message" : "test test test test"
    },
    {
       "ID" : "007",
       "Message" : null
    }
]

I can perform an ng-repeat on the above and filter null's via:

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

But how can i filter the empty strings e.g:

"Message" : " "

Thanks

like image 307
Oam Psy Avatar asked Jul 28 '14 08:07

Oam Psy


3 Answers

We can simply use ng-if here:

<div ng-repeat="data in myData " ng-if="data.Message">
 {{ data.ID }}
 {{ data.Message }}
</div>
like image 198
Anil Sharma Avatar answered Nov 19 '22 03:11

Anil Sharma


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)
}
like image 19
Edminsson Avatar answered Nov 19 '22 05:11

Edminsson


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

like image 7
Rahil Wazir Avatar answered Nov 19 '22 05:11

Rahil Wazir