具有单输入和许多条件的角度滤波器

时间:2015-01-09 00:06:50

标签: javascript angularjs

制作小提琴:http://jsfiddle.net/L3wra2kL/1/

我的期望是: 搜索:'house paris' - >结果这一行:Sell house in Paris

我真的不知道如何做到这一点:单独的单词并使它们成为我的过滤器的'OR条件'......

任何想法?

2 个答案:

答案 0 :(得分:2)

您可以制作自己的自定义过滤器。以下是与您提供的示例集成的简单实现的示例

过滤

app.filter('contains', ['$filter', function(filter) {
    return function (collection, query) {
        var arr = query ? query.toLowerCase().split(/\s+/) : [];
        for (var i = 0; i < arr.length; i += 1) {
            collection = filter('filter')(collection, arr[i]);
        }
        return collection;
    }
}]);

Working Fiddle

答案 1 :(得分:0)

您可以观看搜索更改以及是否有新值 - 只需将其拆分为单词并按此单词过滤原始数组。

 <div ng-app="app">
  <div ng-controller="AppCtrl">
    <p>Name: <input type="text" ng-model="search"></p>
    <ul>
      <li ng-repeat="x in articles">
      {{ x }}
      </li>
    </ul>
  </div>
</div>

角度代码:

(function(angular){
     angular.module('app',[])
     .controller('AppCtrl', function($scope, $filter){
         $scope.articlesOriginal = ['Sell house in Washigton', 'Sell house in Paris', 'Sell car in London', 'Sell car in Washigton'];
         $scope.articles = $scope.articlesOriginal;

       $scope.$watch('search', function(newVal, oldVal){
        if(newVal!==oldVal){
          var filteredList, splitedWords, resultList=$scope.articlesOriginal;

          splitedWords = newVal.trim().split(/\s+/);

          angular.forEach(splitedWords, function(word){
            resultList = $filter('filter')(resultList, word);
          });

          $scope.articles = resultList;

        }
    });
    });
 })(angular);

Updated code on fiddle