AngularJS严格过滤字段为空时如何显示所有值?

How to show all values when AngularJS strict filter field is empty?

我有一个 table 可以按几列过滤。过滤很严格。启动数据时,它会显示所有值。但是,在按某些列过滤并返回空选项以显示所有值后,它显示空 table。如何仅对非空值应用严格过滤器?

<select
    ng-model="search.column1">
    <option value=''></option>
    <option ng-repeat="e in vm.getExample value="{{e.column1}}">{{e.column1}}</option>
</select> 

<select
    ng-model="search.column2">
    <option value=''></option>
    <option ng-repeat="e in vm.getExample value="{{e.column2}}">{{e.column2}}</option>
</select> 

<table>
    <tr>
        <th>Column1</th>
        <th>Column2</th>
    </tr>

    <tr ng-repeat="e in vm.getExample | filter:search:true">
        <td>{{ e.column1 }}</td>
        <td>{{ e.column2 }}</td>
    <tr>
</table>

您的问题在于使用 filter:

您应该将 filter:search:true 更改为 filter:search

第三个参数filter是比较器。在这种情况下,您不需要它:

Comparator which is used in determining if values retrieved using expression (when it is not a function) should be considered a match based on the expected value (from the filter expression) and actual value (from the object in the array).

如果您想了解更多关于比较器的知识,我建议您阅读 this excellent answer (SO)。


您的代码的工作片段:

var app = angular.module('testApp', []);
app.controller('testController', ['$scope', function($scope) {
  this.getExample = [{
    'column1': 1,
    'column2': 2
  }, {
    'column1': 3,
    'column2': 4
  }, {
    'column1': 5,
    'column2': 6
  }];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp" ng-controller="testController as vm">
  <select ng-model="search.column1">
    <option value=''></option>
    <option ng-repeat="e in vm.getExample" value="{{e.column1}}">{{e.column1}}</option>
  </select>

  <select ng-model="search.column2">
    <option value=''></option>
    <option ng-repeat="e in vm.getExample" value="{{e.column2}}">{{e.column2}}</option>
  </select>

  <table>
    <tr>
      <th>Column1</th>
      <th>Column2</th>
    </tr>

    <tr ng-repeat="e in vm.getExample | filter:search">
      <td>{{ e.column1 }}</td>
      <td>{{ e.column2 }}</td>
      <tr>
  </table>
</div>

在控制器中创建自定义过滤器:

$scope.filterMyData = function (input, searchParam) {

     if (searchParam == '')
          return true;

     return angular.equals(input, searchParam);
}

并更改为:

<tr ng-repeat="e in vm.getExample | filter:search:filterMyData">