Scott Wright Scott Wright - 7 months ago 11
Javascript Question

Angular custom filter logs out as working with some matches but filters out all results

I think I may have a syntax error in here somewhere. The idea is that the user selects currencies that they are interested in. Subsequently I only want to print out rows of the currencies table that have a matching currency. I am using a custom filter to achieve this.

I want to either fix my custom filter syntax or look at a way to use a built in filter to achieve the same thing.

//directive html
<table class="table table-striped">
<thead>
<tr>
<th>Currency</th>
<th>Gram Price</th>
<th>Ounce Price</th>
<th>Kilo Price</th>
<th>24 hr Change</th>
<th>1 yr Change</th>
<th>10 yr Change</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="quote in vm.quotes | selectedCurrencies:vm.selectedCurrencies()">
<th scope="row">{{quote.currency}}</th>
<td>{{quote.price}}</td>
<td>{{quote.ouncePrice}}</td>
<td>{{quote.kiloPrice}}</td>
<td>{{quote.change.d1}}</td>
<td>{{quote.change.y1}}</td>
<td>{{quote.change.y10}}</td>
</tr>
</tbody>
</table>

//filter
angular.module('bgAngularTest').filter('selectedCurrencies', function($log) {
return function(quotes, selectedCurrencies) {
if(!quotes.length){
return;
}
return quotes.filter(function(quote) {
selectedCurrencies.forEach(function(cur){

$log.info(quote.currency +' ==== '+ cur + ' ?');

if(cur === quote.currency){
$log.info('match');
return true;
}
})
return false;
});
};
});

//example of quote data

{
"quotes": [{
"currency": "USD",
"price": 40.55,
"symbol": "$",
"change": {
"d1": 0.0116,
"y1": 0.0425,
"y10": 1.1029
}
}, ...]
}

//example of currency list

["RUB","USD","EUR"]

Answer

Your selectedCurrencies.forEach doesn't actually return anything, because the callback is internal to the forEach:

if(cur === quote.currency){
    $log.info('match');
    return true;
}

You return false all the time, and all your items are filtered out. Try this instead:

return quotes.filter(function(quote) {
    return selectedCurrencies.some(function(cur){ // if at least one currency matches return true
        return cur === quote.currency;
    });
});