filterpolymerdom-repeat

Polymer: multiple filters in template dom-repeat


I have a simple dom repeat like this:

<template is="dom-repeat" items="{{projects}}" as="project" filter="{{computeFilter(searchString)}}">
[[project.name]] - [[project.number]]
</template>

<paper-input name="filter-name" label="Filter by project name" value="{{searchString}}"></paper-input>

And there is a function that filters the projects by name:

computeFilter: function(keyword) {
  if (!keyword) {
    return null;
  } else {
    keyword = keyword.toLowerCase();
    return function(project) {
      var name = project.name.toLowerCase();
      return (name.indexOf(keyword) != -1);
    };
  }
}

All good. Now, how would I go about adding another filter, if for example I'd also like ot filter by project number?

I would have another paper button binding to {{searchString2}}, but then how would I link this to a filter - in other words, how can I set up multiple filters on a dom-repeat?


Solution

  • There's a way to filter a dom-repeat using multiple filters.

    First, here's the template:

    <paper-input name="filter-name" label="Filter by project name" value="{{filterText::input}}"></paper-input>
    <paper-input name="filter-name" label="Filter by project type" value="{{filterText2::input}}"></paper-input>
    <template id="resultList" is="dom-repeat" items="{{ projects }}" filter="filterProject" as="project">
      <div>
        [[project.name]] - [[project.number]]
      </div>
    </template>
    

    You must define for each filter an observer to refresh the filter:

    this.$.resultList.render();
    

    Then, you must use a filter function with your filters:

    filterProject: function(item) {
        return (this.filterText && item.name.match(new RegExp(this.filterText, 'i'))) || 
          (this.filterText2 && item.name.match(new RegExp(this.filterText2, 'i')));
      },
    

    Here you can see an example of this method.