使用搜索输入字段过滤 ng-repeat 中的嵌套对象
Filtering nested objects in ng-repeat with a search input field
我正在尝试使用搜索文本框过滤 ng-repeat 中的嵌套对象。
给定以下对象:
$scope.items = {
"1": {
name: "First Item",
tag: "first"
},
"2": {
name: "Second Item",
tag: "second"
}
};
我想做这样的事情:
<input type="text" name="serchBox" ng-model="searchByName">
<p ng-repeat="(key, values) in items | filter:{name: searchByName}">
Using both {{key}} and {{values.name}}
</p>
这确实不行。我尝试了很多东西,但无法使其正常工作。 我不想改变我的对象。我搜索了很多,但没有找到适合我需要的东西。
我终于找到了我自己的问题的答案。
我只需要创建自己的过滤器并使用正则表达式检查对象内的属性是否具有所需的值:
app.filter('customSearchFilter', function() {
return function(input, term) {
var regex = new RegExp(term || '', 'i');
var obj = {};
angular.forEach(input, function(v, i){
if(regex.test(v.name + '')){
obj[i]=v;
}
});
return obj;
};
});
并以这种方式在 HTML 中应用它:
<input type="text" ng-model="searchName" />
<ul>
<li ng-repeat="(key, val) in items | customSearchFilter:searchName">Both {{key}} and {{val.name}}</li>
</ul>
我创建这个 Plunker 是为了展示我的解决方案
如果您不需要在其他任何地方重复使用您的过滤器,您可以在控制器中编写您的过滤函数。
scope.customSearchFilter = function(term){
return function(item) {
var regex = new RegExp(term || '', 'i');
return regex.test(item.name + '');
};
};
过滤器参数是单个项目,而不是数组。
这里是例子。第一个变体是模型,第二个是普通范围:
我正在尝试使用搜索文本框过滤 ng-repeat 中的嵌套对象。
给定以下对象:
$scope.items = {
"1": {
name: "First Item",
tag: "first"
},
"2": {
name: "Second Item",
tag: "second"
}
};
我想做这样的事情:
<input type="text" name="serchBox" ng-model="searchByName">
<p ng-repeat="(key, values) in items | filter:{name: searchByName}">
Using both {{key}} and {{values.name}}
</p>
这确实不行。我尝试了很多东西,但无法使其正常工作。 我不想改变我的对象。我搜索了很多,但没有找到适合我需要的东西。
我终于找到了我自己的问题的答案。
我只需要创建自己的过滤器并使用正则表达式检查对象内的属性是否具有所需的值:
app.filter('customSearchFilter', function() {
return function(input, term) {
var regex = new RegExp(term || '', 'i');
var obj = {};
angular.forEach(input, function(v, i){
if(regex.test(v.name + '')){
obj[i]=v;
}
});
return obj;
};
});
并以这种方式在 HTML 中应用它:
<input type="text" ng-model="searchName" />
<ul>
<li ng-repeat="(key, val) in items | customSearchFilter:searchName">Both {{key}} and {{val.name}}</li>
</ul>
我创建这个 Plunker 是为了展示我的解决方案
如果您不需要在其他任何地方重复使用您的过滤器,您可以在控制器中编写您的过滤函数。
scope.customSearchFilter = function(term){
return function(item) {
var regex = new RegExp(term || '', 'i');
return regex.test(item.name + '');
};
};
过滤器参数是单个项目,而不是数组。
这里是例子。第一个变体是模型,第二个是普通范围: