Search code examples
angularjsangular-ui-grid

AngularJS ui-grid re-using a custom filter


I have a basic grid with a couple of columns that are ranges, i.e. 10 - 50, 0 - 9, etc. and I've written a custom filter on one of the columnDefs;

filter: {
  condition: function(searchTerm, cellValue) { ... }
}

The filter works perfectly, but I'd like to strip it out and re-use it, only I can't figure out how.

I've tried defining it in the controller as function rangeFilter(...) and vm.rangeFilter = rangeFilter and then assigning it to the condition as grid.appScope.filterRange(searchTerm, cellValue) but that doesn't work.

I'm not really sure how else I'd do it, I haven't been able to find anything in the documentation or by googling for it.

Here's a plunkr of it in action; http://next.plnkr.co/edit/mbtXzfWqBg8FIALu


Solution

  • As you did, move the function out of the column definitions.

    function rangeFilter() {
        ...
    }
    

    And in the column definitions pass a reference to the function in both.

    vm.gridOptions = {
        ...
        columnDefs: [
          // default
          { field: 'name' },
          { field: 'range', cellFilter: 'range', filter: {condition: rangefilter}},
          // I want to reuse the same filter as 'range' for this column somehow...
          { field: 'anotherRange', cellFilter: 'range', filter: {condition: rangefilter}}
        ],
        ...
      };
    

    Plunker