简体   繁体   English

AngularJS过滤器:智能搜索

[英]AngularJS filter: Smart search

I am trying to filter results in an ng-repeat , but with a "smart search" feature, ie. 我正在尝试在ng-repeat过滤结果,但是具有“智能搜索”功能,即。 using multiple keywords to search. 使用多个关键字进行搜索。 The collection is a complex array of objects, containing objects. 集合是对象的复杂数组,其中包含对象。

According to Angular Docs: $filter , you can use {$: "keyword"} with the filter function to deepfilter, but I have not gotten it to work. 根据Angular Docs:$ filter ,您可以使用带有过滤器功能的{$: "keyword"}来对deepfilter进行过滤,但是我没有使它起作用。

Snippet: 片段:

.filter('smartsearch', function () {
    return function (collection, keywords) {
    if (!keywords) {
        return collection;
    } else {
        keywords = keywords.split(" ");
        _.each(keywords, function (word) {
            collection = _.filter(collection, {$: word});
        });
        return collection;
    }
}

It seems to return an empty array ( [] ) each time, even though I know I am using a matching keyword 似乎每次都返回一个空数组( [] ),即使我知道我使用的是匹配关键字

UPDATE UPDATE

Got it working thanks to @gravityplanx pointing me in the right direction, below is the working solution: 感谢@gravityplanx使我朝着正确的方向工作,以下是可行的解决方案:

.filter('smartsearch', ['$filter', function ($filter) {
        return function (collection, keywords) {
            if (!keywords) {
                return collection;
            } else {
                keywords = keywords.split(" ");
                $.each(keywords, function (k, v) {
                    collection = $filter('filter')(collection, {$: v});
                });
                return collection;
            }
        }
    }]);

You're using underscores filter method, when you want to be using Angular's. 当您想使用Angular时,您正在使用下划线过滤器方法。

Simply change _.filter( to $filter( . 只需将_.filter(更改为$filter(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM