Angular UI Grid filter only applies to beginning of cell value
Asked Answered
F

2

6

I'm using an Angular UI Grid in my app. I set enableFiltering to true in the options which made some filter boxes show up above my columns. This is great, but the filters don't work exactly as desired.

If a cell contains the text "I like pizza" and I type "I like", that cell's row is shown as a match. I would also think that if I type "pizza", the "I like pizza" cell/row should show up, but that's not the case.

How can I get the filters to allow searching anywhere in the text, not just from the beginning?

Frodine answered 3/6, 2015 at 19:45 Comment(4)
The default is STARTS_WITH, but you can change it: github.com/angular-ui/ng-grid/issues/2839Thorbert
@BradBarber that looks like the exact thing I want, although it's not clear how to actually use it. Any ideas?Frodine
In the columnDef where you want to use it, you'd add the following: filter: {condition: uiGridConstants.filter.CONTAINS}Thorbert
That did it. Thanks. If you put that as an answer, I'll accept it.Frodine
T
5

You can use filter: {condition: uiGridConstants.filter.CONTAINS} in the column definition to allow that column to search anywhere in the text.

Here's a sample column definition with this in place:

columnDefs: [
  // default
  { field: 'name',
    filter: {condition: uiGridConstants.filter.CONTAINS} },
  ...
Thorbert answered 3/6, 2015 at 20:27 Comment(3)
BTW, reader, don't forget to include uiGridConstants in your dependency injection.Frodine
Is there an advantage to this over writing a function?Brighton
@azium, I prefer to use any capabilities provided by a framework if it's available...they usually implement it better than I would. In this case they implemented the CONTAINS filter with a regex instead of indexOf which I think is a little faster (github.com/angular-ui/ng-grid/blob/master/src/js/core/services/…).Thorbert
B
1

You can pass a custom filter object that takes a condition property, which can be a function that takes searchTerm and cellValue. Will display if the function returns true. Plunkr

  { field: 'name', filter: {
    condition: function(searchTerm, cellValue) {
      return cellValue.indexOf(searchTerm) > -1
    }
  }}
Brighton answered 3/6, 2015 at 20:15 Comment(1)
BTW, even though I didn't think this was the best way to accomplish what I was originally after, this code was helpful to me in a different way later, so thanks.Frodine

© 2022 - 2024 — McMap. All rights reserved.