javascript - Angular 过滤对象的多个字符串

标签 javascript html angularjs arrays json

我有一个 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/

相关文章:

javascript - 使用 jQuery 确定单击了哪个元素 ID 或类?

html - 带 Mootools 的子菜单 (Joomla 1.5)

html - 如何在视频标签中显示音量控制?

css - 如何从弹出窗口中删除背景控件?

javascript - Symfony2 Bundles 资源文件丢失

javascript - 如何将这两个正则表达式合并为一个?

javascript - 使用 Javascript 切换图像 src 属性

html - Parsoid - 在本地解析维基文本

node.js - 使用 Restify 提供单页 Angular 应用程序

javascript - 无法使用输入类型在 IE9 中获取 slider =使用 Angular JS 的范围