我有一个 JSON 形式的数组(项目)。对象项目具有以下字段:
"name":"pname",
"id":"1",
"keywords":"aab bb cc"
我使用
在 div 标签中显示这些对象<div ng-repeat="p in projects | filter : searchText">
{{p.name}}, {{p.id}} etc.
</div>
我将过滤器连接到输入表单 ng-model="searchText"
并希望使用多个字符串进行搜索。例如搜索:“pname aa bb”应该会显示上述项目。
我知道我必须使用自定义过滤器并拆分搜索文本。但用于过滤字符串数组的方法似乎不适用于 JSON 对象。有什么区别?
尝试简单的字符串数组,例如['aab', 'bb', 'cc']
对对象数组不起作用:
.filter("myFilter", function(){
return function(input, searchText){
var returnArray = [];
var searchTextSplit = searchText.toLowerCase().split(' ');
for(var x = 0; x < input.length; x++){
var count = 0;
for(var y = 0; y < searchTextSplit.length; y++){
if(input[x].toLowerCase().indexOf(searchTextSplit[y]) !== -1){
count++;
}
}
if(count == searchTextSplit.length){
returnArray.push(input[x]);
}
}
return returnArray;
}
});
如何使其适用于对象?
最佳答案
But the approach that works to filter string arrays does not seem to work for JSON objects. What is the difference?
当filter
过滤器的表达式
参数是字符串
时,Angular将尝试匹配给定的字符串
> 如果匹配的项目属于 object
类型,则仅一个特定键值对。
供引用,来自 Angular 文档:
The string is used for matching against the contents of the array. All strings or objects with string properties in array that match this string will be returned. This also applies to nested object properties.
您似乎想要的行为是将字符串
与多个键值对中的值进行匹配。
也就是说,您可以利用可以将表达式
参数传递给谓词函数
的事实来引入更智能的匹配行为。
查看我的以下 Plunker 以获得可行的解决方案。可以进一步优化或调整以处理更多情况,即处理数组值。
关于我的解决方案需要注意的一点是,即使您的对象具有嵌套属性,它也支持匹配术语。
关于javascript - Angular 过滤对象的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41496603/