如果您查看下面的代码,我想使用文本<input>
按多个成分过滤每个菜单项 - 例如,如果用户在{中输入“beef,bacon” {1}},该应用程序将返回所有菜单项,其中包含牛肉或培根作为成分。
我目前正在尝试使用ng-filter执行此操作,我猜我需要为此创建自定义过滤器。这是错误的方法吗?有没有办法动态链接过滤器呢?
这里有一些代码可以理解我的问题 -
我的搜寻模式: - 注意:使用ng-list将字符串转换为子字符串数组
<input>
我的ng-repeat循环: - 注意:使用自定义过滤器将我的每个成分连接成一个字符串
<div ng-init="searchString=[]">
<input type="text" ng-model="searchString" ng-list>
</div>
我的数据结构
<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>
答案 0 :(得分:2)
(我知道这可能是一个死的问题,但我发现它也是如此:)
需要自定义过滤器,因为您要过滤与搜索列表共享至少一个成分的菜单项(即非空数组交集)。问题中使用的过滤器filter:{ ingredients : searchString }
不会以这种方式进行过滤,也不会从official doc中将任何其他过滤器内置到Angular中。
创建自定义过滤器很简单;将新功能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中查看。
答案 1 :(得分:1)
您可以创建自定义过滤器,或使用带谓词(函数)的角度过滤器
{ filter_expression | filter:predicateFunction }}
当然,您的函数存在于控制器的范围内,其中搜索字符串是可见的
谓词函数可用于写入任意过滤器。该 为数组的每个元素调用函数。最终的结果是 谓词返回true的那些元素的数组。