Angular自定义过滤器在处理某些匹配时注销,但会过滤掉所有结果

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

本文关键字:过滤 结果 注销 过滤器 自定义 处理 Angular      更新时间:2023-09-26

我想我可能在这里的某个地方有语法错误。这个想法是用户选择他们感兴趣的货币。随后,我只想打印出货币表中有匹配货币的行。我正在使用自定义过滤器来实现这一点。

我想修复我的自定义过滤器语法,或者寻找一种使用内置过滤器的方法来实现同样的目的。

//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"]

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