1

I have a table which can be filtered by several columns. The filter is strict. When the data is initiated, it shows all values. However, after filtering by some column and getting back to empty option to show all values, it shows an empty table. How to apply a strict filter only to non-empty values?

<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>
Mistalis
  • 17,793
  • 13
  • 73
  • 97
Justinas Jakavonis
  • 8,220
  • 10
  • 69
  • 114

2 Answers2

2

Your issue was in the use of filter:

You should change filter:search:true to filter:search.

The third parameter the filter is a comparator. In this case, you don't need it:

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).

If you want to learn more a bit about comparators, I recommand you to read this excellent answer (SO).


Working snippet of your code:

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>
Mistalis
  • 17,793
  • 13
  • 73
  • 97
1

Created custom filter in controller:

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

     if (searchParam == '')
          return true;

     return angular.equals(input, searchParam);
}

And changed to:

<tr ng-repeat="e in vm.getExample | filter:search:filterMyData">
Justinas Jakavonis
  • 8,220
  • 10
  • 69
  • 114