michas84
michas84

Reputation: 177

angular custom filtering in ngTables

I'm trying to do some custom filtering in ngTables (simmilar to this example), but with text input field. I have set of columns with standard text input filters and for some of them I want to use my own filtering function, not default angular $filter('filter')(array, params.filter()), but something like $filter('myOwnFilter')(array, params.filter())

Filtering happens in my controller:

var orderedData = params.filter() ? $filter('filter')(array, params.filter()) : array;

What I have:

<td class="text-left" data-title="'Name'" filter="{ 'Column': 'myOwnFilter' }" data-sortable="'Column'">
  {{ array.Column }}
</td>

and the template:

<script type="text/ng-template" id="ng-table/filters/myOwnFilter.html">
  <input type="text" name="myOwnFilter" data-ng-model="params.filter()[name]" data-ng-if="filter == 'myOwnFilter'" class="input-filter form-control"/>
</script>

Upvotes: 3

Views: 5161

Answers (2)

Dan Mihai Patrascu
Dan Mihai Patrascu

Reputation: 192

Let's say you want to add a filter that shows only the rows that have the property avg greater-than your filter:

View

<td data-title="'Average'" sortable="'avg'" filter="{ 'min': 'number' }">

Controller

vm.filtered = params.filter() ? filterData(params, vm.filtered) : vm.filtered;

And the custom filter

function filterData(params, data) {
              var min;
              if (params.filter() && params.filter().min) {
                  //remove default params.filter().min filter
                  min = params.filter().min;
                  delete params.filter().min;
                  //filter data by min
                  data = _.filter(data, function (d) { return min <= d.avg; });
              }
              //use the normal filter
              data = params.filter() ? $filter('filter')(data, params.filter()) : data;
              if (min != undefined)//add it back
                  params.filter().min = min;
              return data;
          }

Upvotes: 0

cleftheris
cleftheris

Reputation: 4839

As answered in this question https://stackoverflow.com/a/27296677/61577 you must use a custom "comparator" function as a third argument in your controller. A simple example

var myCustomComparator = function(value, searchTerm) {
    return (value || '').indexOf(searchTerm) > -1;
}

then in your getData callback

var orderedData = params.filter() ? $filter('filter')(array, params.filter(), myCustomComparator) : array;

Just note that you must inspect the params.filter() in case you need different comparators for different columns/fields.

The angular documentation for filter comparator

Upvotes: 4

Related Questions