我有一个对象数组:
scope.values = [
{'key1':'valueA', 'key2': 'valueD'},
{'key1':'valueB'},
{'key1':'valueC'}
]
而且我想过滤搜索输入,其中可以包含多个用逗号或空格分隔的单词:
<input ng-model="scope.search"></input>
我们可以如下列出数组:
<p ng-repeat="index, obj in scope.values | filter:scope.search"></p>
但是,这仅适用于一个输入。当我有多个输入时我该怎么办约翰·杜伊。
请注意,我希望它是有条件的。因此,如果找到了John或Doe,则不会,而是找到John和Doe时。
我认为内置过滤器无法做到这一点。您可能想要的是自定义过滤器,如文档here(大约位于页面的一半)和官方教程here中所述。
例如,此自定义过滤器应执行您想要的操作:
app.filter("multiSearch", [ function() { //"data" is your searchable array, and "search" is the user's search string. return function(data, search) { //Get an array of search values by splitting the string on commas and spaces. var searchArray = search.toLowerCase().split(/[, ]/); //Use javascript's native Array.filter to decide which elements to cut and to keep. return data.filter(function(item) { //If any attribute of the item contains any of the search words, keep it. for (var attribute in item) { for (var searchElement of searchArray) { if ( String(item[attribute]) .toLowerCase() .includes(searchElement) ) { return true; } } } //Not a match. Cut it from the result. return false; }); }; } ]);
然后在您的html中可以这样称呼它:
<p ng-repeat="index, obj in scope.values | multiSearch:scope.search"></p>
如注释中所建议,您可能考虑的另一件事是完全放弃使用过滤器,而只在控制器内部运行逻辑。您可以使用上面示例过滤器中提供的许多逻辑-您只需实现自己的系统即可在搜索查询更改时运行过滤逻辑。避免在angularjs中使用过滤器有很多好处,但这是另一个主题。