AngularJS按任意数量的过滤器过滤

时间:2013-08-05 17:21:20

标签: javascript angularjs

我有一个搜索框,其中包含一系列由空格分隔的术语,这些术语使用string.split(' ')拆分为数组。有没有办法从该数组应用任意和可能大量的过滤器?

3 个答案:

答案 0 :(得分:4)

与Thad类似,但实际上是创建自定义过滤器模块而不是使控制器混乱。这就是它对我有用的方式:

<input type="text" ng-model="query">
<li ng-repeat="object in objects | filterFunction:query"> {{object.state}}

.filter('filterFunction', function() {

  return function (objects, query) {

    // objects is the array being filtered
    // query is the value you passed in

    array = query.split(' ');

    for (var i = 0, len = objects.length; i < len; i++) {
      // filter the crap out of these objects
    }

  }
});

答案 1 :(得分:0)

我认为这是您需要使用谓词函数过滤器而不是字符串过滤器...

像这样(伪代码):

<!--html-->
<ul>
    <li ng-repeat="object in objects | filter:filterFunction">
        {{object.description}}
    </li>
</ul>

<!-- controller -->
$scope.objects = [ your data here ];

$scope.filterFunction = function(searchVal) {
    // write code that returns true or false depending
    // on whether or not after you split searchVal any 
    // of the elements are in your data
}

我没试过这个,但这就是文档说的方法。

-Thad

答案 2 :(得分:0)

这里很棒的多重过滤器:
https://gist.github.com/i8ramin/5825377

Angular JS过滤器的行为很像内置过滤器,但允许您使用多个值进行过滤,空格分隔。例如&#34;大橙色圆&#34;

相关问题