NVO NVO - 3 months ago 25
AngularJS Question

Angular multiple filter, second filter is empty?

I have an ng-repeat (jade):

.col-lg-4.col-md-4.col-sm-6.col-xs-12.product.product-grid(ng-repeat='item in collection | product_sex:filter_sex | product_stock:stockKind')


In my app.js I have two filters:

.filter('product_sex', function(){
return function(input, sex){

if(input == undefined){
input = [];
}
var output = [];

if(sex == 'undefined' || sex =='all'){
output = input;
}

for(var i =0; i < input.length; i++){
var item = input[i];

if (item.product.sex == sex){
output.push(item);
}
}


return output;
}
})
.filter('product_stock', function(){
return function(input, stockKind){

if(input == 'undefined'){
input = [];
}

var output = [];

if (stockKind == 'undefined' || stockKind == 'all'){
output = input;
}

for(var i=0; i< input.length; i++){
var item = input[i];

if(item.stock < 0 && item.status != 'Niet leverbaar' && stockKind == 'online'){
output.push(item);
}else if(item.stock > 0 && item.status != 'Niet leverbaar' && stockKind =='fysiek'){
output.push(item);
}
}


}
})


I want to apply both filters to my ng-repeat. The first filter works fine, but when I add the second filter (as in the example) it will return nothing. The angular error logs says
TypeError: Cannot read property 'length' of undefined
for the for loop in the
product_stock filter
. I can't see what i'm doing wrong, so I'am wondering if you can help me again?

In my controller I fill
$scope.stockKind
and
$scope.filter_sex
with 'all'. Later i make it possible to change the value of that when clicking on a link, like
ng-click='stockKind="online"'

Answer

Your error is in the following part of the code

if(input == 'undefined'){
    input = [];
}

You should replace it by

if(input == null){
    input = [];
}

OR

if(input === undefined || input === null){
    input = [];
}

Both are exactly the same