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
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;
}
});