【问题标题】:angularjs - ngRepeat with OR filterangularjs - ngRepeat 与 OR 过滤器
【发布时间】:2014-01-21 01:34:08
【问题描述】:

我有一个包含项目的列表(名称:字符串,年龄:Int,检查:布尔值)。 此列表以 ng-repeat 显示。 我想让用户使用搜索字段搜索列表,搜索不得影响选中值。

  • 只有在用户在搜索字段中输入内容时才会触发搜索
  • 如果搜索字段已填满,则搜索应照常过滤,不得过滤掉选中的项目。

我尝试创建自定义过滤器。我在使用 OR 逻辑理解 $filter('filter') 函数时遇到问题。

谁能帮我解开我脑子里的结?

app.filter('mySearchFilter', function($filter) {
    return function(data, searchText) {

        if(!searchText || searchText.length === 0) {
            return data;
        }

        console.log(searchText);

        return $filter('filter')(data, searchText);
        //how can I provide additional, OR-concatinated, filter-criteria?
    }
});

查看我的 plunk 以获取最小示例代码。

http://plnkr.co/edit/3xHLOrSPD3XZy2K9U2Og?p=preview

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:

    据我了解,您正在寻找联合功能。 Underscore 提供了这样的功能。有了这个,你可以这样写你的过滤器:

    app.filter('mySearchFilter', function($filter) {
       return function(data, searchText) {
    
           if(!searchText || searchText.length === 0) {
               return data;
           }
    
           var allChecked = data.filter(function(d){return d.checked});
           var allMatched = $filter('filter')(data, searchText);
           return _.union(allMatched, allChecked);
       }
    });
    

    看看:http://documentcloud.github.io/underscore/#union,别忘了包含脚本:

    <script src="http://documentcloud.github.io/underscore/underscore.js"></script>
    

    PLUNKR

    【讨论】:

    • 谢谢你,迈克尔,你的解决方案。我是 AngularJS 的新手,并且一直在努力使用 javascript。我通常在 scala 中工作,并且习惯了它的舒适性、类型安全性等......下划线消除了一些痛苦;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2014-05-31
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    相关资源
    最近更新 更多