angular filter with dynamic list of attributes to search

℡╲_俬逩灬. 提交于 2019-12-11 08:18:22

问题


my goal it to create a search box that will filter a collection either by searching all the fields, or by a specific attribute. this will be determined by a select.

so, here's what i got

it is able to search by specific attribute, as expected, using this custom filter: my html-

<tr ng-repeat="smartphone in smartphones | filter: search ">

JS-

$scope.search = function (item){
  if (item[$scope.selectedSearchBy].indexOf($scope.query)!=-1) {
    return true;
  }
  return false;
};

note that in order to search on all of the fields, i can change my ng-repeat to be filtered as following:

<tr ng-repeat="smartphone in smartphones | filter:query ">

and it will work.

However, both will not work together.

my question is:

how can i create a truly generic binded dropdown and search box. that will receive the searchable attributes and take care of the filtering appropriatly? (preferably without using ng-show or making DOM manipulations).

would love to supply more details if needed.


回答1:


How about this?

The filter filter supports the object syntax as an argument where the key is the search field and the value is the search query. For example, in your template:

<tr ng-repeat="smartphone in smartphones | filter:{brand: query}">

would filter the list by brand according to the query, and

<tr ng-repeat="smartphone in smartphones | filter:{'$': query}">

would search all the fields. So if only there's a way to do this

<tr ng-repeat="smartphone in smartphones | filter:{selectedSearchBy: query}">

where the key of the object is set to the value of the variable selectedSearchBy, but this isn't possible in javascript, so I wrote a helper function to do it:

<tr ng-repeat="smartphone in smartphones | filter:filterParam(selectedSearchBy, query)">


来源:https://stackoverflow.com/questions/23953604/angular-filter-with-dynamic-list-of-attributes-to-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!