Javascript AngularJS过滤-多个表达式还是动态链接ng过滤器?
如果你看一下下面的代码,我想用一个文本Javascript AngularJS过滤-多个表达式还是动态链接ng过滤器?,javascript,angularjs,Javascript,Angularjs,如果你看一下下面的代码,我想用一个文本按多种成分过滤每个菜单项-例如,如果用户在中键入“beef,bacon”,应用程序将返回所有菜单项,其中牛肉或培根作为成分 我目前正在尝试使用ng过滤器来实现这一点,我想我需要创建一个自定义过滤器来实现这一点。这是错误的方法吗??是否有一种方法可以动态链接过滤器 这里有一些代码可以解释我的问题- 我的搜索模式: -注意:使用ng list将字符串转换为子字符串数组 您可以创建自定义过滤器,或将角度过滤器与谓词(函数)一起使用 当然,您的函数位于控制器的作用域
按多种成分过滤每个菜单项-例如,如果用户在
中键入“beef,bacon”,应用程序将返回所有菜单项,其中牛肉或培根作为成分
我目前正在尝试使用ng过滤器来实现这一点,我想我需要创建一个自定义过滤器来实现这一点。这是错误的方法吗??是否有一种方法可以动态链接过滤器
这里有一些代码可以解释我的问题-
我的搜索模式:
-注意:使用ng list将字符串转换为子字符串数组
您可以创建自定义过滤器,或将角度过滤器与谓词(函数)一起使用 当然,您的函数位于控制器的作用域中,搜索字符串可见 谓词函数可用于编写任意筛选器。这个 为数组的每个元素调用函数。最终的结果是 谓词为其返回true的元素的数组 (我知道这可能是一个死问题,但我也发现了:) 需要自定义筛选器,因为您希望筛选与搜索列表至少共享一个成分的菜单项(即非空数组交叉点)。问题中使用的过滤器,
filter:{components:searchString}
不会以这种方式进行过滤,其他任何内置于Angular中的过滤器也不会以这种方式进行过滤
创建自定义过滤器很容易;在$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:{ 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_expression | filter:predicateFunction }}
// 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;
}