自定义列表过滤器

Custom filter for list

本文关键字:过滤器 列表 自定义      更新时间:2023-09-26

我试图使过滤器仅显示与用户输入匹配的列表上的元素。

.filter('removeAcentos', function(){
    return function (source, item) {
    var re = new RegExp("" + item.toLowerCase() + "");
        angular.forEach(source, function(word){
            if(re.test(word.nomeCurso.toLowerCase()) === true){
                return true;
            }
        });
      //
        return false;
    };
})

And on the view:

<li ng-repeat="curso in ctrl.list| removeAcentos: ctrl.input ">
    ... <!-- display items from ctrl.list that match ctrl.input -->
</li>

然而,我不明白为什么它不起作用。我测试了正则表达式和过滤器函数返回true的正确值。的念头吗?

你的函数没有返回数组。函数唯一返回的是false

forEach也不是这项工作的合适工具。尝试使用Array.prototype.filter(),并记住返回新的数组:

.filter('removeAcentos', function(){
    return function (source, item) {
       if(!source){
          return false;
       }  
        var re = new RegExp("" + item.toLowerCase() + "");
       // return filtered array
       return source.filter( function(word){
            return re.test(word.nomeCurso.toLowerCase());
        });
    };
})