Filter by multiple fields in Ionic

2019-08-06 11:31发布

问题:

I've jumped into a half complete Ionic Cordova project, I want the search function to search via product_name or product_code, it currently only filters via product name.

<input type="text" ng-model="search.search"  placeholder="Scan/Enter product" ng-change="setFocus()"/>

<div class="odd" ng-if="focus" ng-repeat="mydata in data | filter:{product_name:search.search, product_code:search.text}">

TIA

回答1:

You should create custom orFilter:

angular.module('app', []).controller('ctrl', function($scope){
  $scope.data  = [
    {product_name:'Prod1', product_code:'1112'},
    {product_name:'Prod2', product_code:'2223'},
    {product_name:'Prod3', product_code:'3334'}
  ]
}).filter('orFilter', function(){
  return function(data, props, search){
    if(!search)
      return data;
    
    search = search.toLocaleLowerCase();
    return data.filter(function(x){ 
      for(var prop of props)
        if(x[prop].toLocaleLowerCase().indexOf(search) != -1)
         return true;
      return false;
    });
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  <input type='text' ng-model='search' ng-init='search="2"'/>
  <ul>
    <li ng-repeat='item in data | orFilter: ["product_name", "product_code"]: search'>
      {{item | json}}
    </li>
  </ul>
</div>