我想我可能在某处遇到语法错误。这个想法是用户选择他们感兴趣的货币。随后我只想打印出具有匹配货币的货币表行。我正在使用自定义过滤器来实现此目的。
我想要修复我的自定义过滤器语法,或者想要使用内置过滤器来实现同样的目的。
//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"]
答案 0 :(得分:1)
您的selectedCurrencies.forEach
实际上并没有返回任何内容,因为回调是forEach
内部的:
if(cur === quote.currency){
$log.info('match');
return true;
}
您会一直返回false
,并且所有项目都会被过滤掉。试试这个:
return quotes.filter(function(quote) {
return selectedCurrencies.some(function(cur){ // if at least one currency matches return true
return cur === quote.currency;
});
});