如果您看一下下面的代码,我想使用文本 <input>
按多种成分过滤每个菜单项 - 例如,如果用户在 <input>
中输入“牛肉,培根” ,该应用程序将返回所有以牛肉或培根为原料的菜单项。
我目前正在尝试使用 ng-filter 执行此操作,我猜我需要为此创建一个自定义过滤器。这是错误的方法吗?有没有办法改为动态链接过滤器?
这里有一些代码可以解释我的问题 -
我的搜索模型: - 注意:使用 ng-list 将字符串转换为子字符串数组
<div ng-init="searchString=[]">
<input type="text" ng-model="searchString" ng-list>
</div>
我的 ng-repeat 循环: - 注意:使用自定义过滤器将我的每种成分连接成一个字符串
<tr ng-repeat="item in menu | filter:{ category : 'Classics' } | filter:{ ingredients : searchString } ">
<td class="title">{{ item.title }}</td>
<td class="ingredients">
{{ item.ingredients | join:', ' }}
</td>
<td class="price">{{ item.price | currency }}</td>
</tr>
我的数据结构
$scope.menu = [
{
"title" : "New Yorker",
"price" : "4.00",
"ingredients" : [
"Salt Beef",
"Pickles",
"Mustard"
],
"category" : "Classics"
},
{
"title" : "BLT",
"price" : "4.00",
"ingredients" : [
"Bacon",
"Lettuce",
"Tomato"
],
"category" : "Classics"
}
]
最佳答案
(我知道这可能是一个死问题,但我也发现了:)
需要自定义过滤器,因为您要过滤与搜索列表共享至少一种成分的菜单项(即非空数组交集)。问题中使用的过滤器,filter:{ ingredients : searchString }
不会那样过滤,Angular 中内置的任何其他过滤器也不会 official doc .
创建自定义过滤器很容易;添加新功能 containsIngredientsFromSearch
到 $scope
:
// Filter functions are called separately for each item on the menu
$scope.containsIngredientsFromSearch = function(menuItem){
// Check every ingredient on the search list ...
for(var i in $scope.searchString) {
var ingredient = $scope.searchString[i];
// ... does it match an ingredient in menuItem.ingredients?
if(menuItem.ingredients.indexOf(ingredient) !== -1) {
// ... if so, stop searching and return true to include this menuItem
return true;
}
}
// No matching ingredient found? Return false to exclude this item.
return false;
}
将过滤器添加到现有的过滤器链中:
<tr ng-repeat="item in menu | filter:{ category : 'Classics' } | filter:containsIngredientsFromSearch">
查看实际效果 on JSBin .
关于javascript - AngularJS 过滤 - 多个表达式或动态链接 ng-filters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20102404/