AngularJS smart-table search within multiple columns

tadasp picture tadasp · Mar 1, 2015 · Viewed 9.1k times · Source

Smart-table has a built in functionality to search through all columns (st-search) or through one desired column (st-search="'firstName'). Is it possible to do a search within several columns (not all)? Example: if I have table like this: name, nickname, address with such data:

  1. John, JJ, Some address
  2. Steve, John, also address
  3. Jane, Jane, John-village

and do a search for 'John' only first two columns should be as result. Is it possible?

Answer

floatingpurr picture floatingpurr · Sep 14, 2015

I have a similar problem and I solved using the hints in this post.

Smart Table doc says:

The stSetFilter replaces the filter used when searching through Smart Table. When the default behavior for stSearch does not meet your demands, like in a select where one entry is a substring of another, use a custom filter to achieve your goals.

and:

Note that st-safe-src is required for the select to properly display all distinct elements in the collection. Should this be omitted, the select would only contain values from elements visible in table, also affected by paging.

You can declare your own filter inside table element in HTML:

<table ... st-set-filter="myCustomFilter" class="table table-striped">

...and your can customize your filter (in your app) through a predicate function. It could work in this way:

// filter method, creating `myCustomFilter` a globally
// available filter in our module
.filter('myCustomFilter', ['$filter', function($filter) {

  // function that's invoked each time Angular runs $digest()
  return function(input, predicate) {
    searchValue = predicate['$'];
    //console.log(searchValue);
    var customPredicate = function(value, index, array) {
      console.log(value);

      // if filter has no value, return true for each element of the input array
      if (typeof searchValue === 'undefined') {
        return true;
      }

      var p0 = value['name'].toLowerCase().indexOf(searchValue.toLowerCase());
      var p1 = value['nickname'].toLowerCase().indexOf(searchValue.toLowerCase());
      if (p0 > -1 || p1 > -1) {
        // return true to include the row in filtered resultset
        return true;
      } else {
        // return false to exclude the row from filtered resultset
        return false;
      }
    }

    //console.log(customPredicate);
    return $filter('filter')(input, customPredicate, false);
  }
}])

I made this little plnkr to see the filter in action