AngularJS 使用一个字段搜索多个关键字

AngularJS search multiple keywords using one field

我是 AngularJS 的新手。我有 3 个输入字段可以为单个 post:

输入最多 3 个关键字
<input type="text" ng-model="Keyword1"></input>
<input type="text" ng-model="Keyword2"></input>
<input type="text" ng-model="Keyword3"></input>

我正在使用 ng-repeat 显示 posts:

ng-repeat="post in posts | filter: searchKeyword"
...

并通过以下方式搜索:

Search Keyword: <input ng-model="searchKeyword.Keyword1">

如您所见,目前仅搜索每个 post 的第一个关键字。我怎样才能只有一个搜索字段来搜索 post 的所有三个关键字?我知道我不能只做

<input ng-model="searchKeyword.Keyword1.Keyword2.Keyword3">

谢谢!

这是我要做的

  1. 写一个自定义过滤器(https://docs.angularjs.org/guide/filter
  2. 在过滤器中将输入拆分为 space(这将为您提供单独的单词)
  3. 一一搜索输入的所有单词

不确定目的是 return 所有匹配至少一个关键字的帖子还是匹配所有关键字的所有帖子。以下是创建自定义过滤器以匹配至少一个词的方法:

<div ng-controller="theController">
  <input ng-model="inputText"/>
  <!-- Use a custom filter to determine which posts should be visible -->
  <ul>
    <li ng-repeat="post in posts | filter:myFilter">{{post}}</li>
  </ul>
</div>

angular.module('theApp', [])
  .controller('theController', ['$scope', function($scope) {
    $scope.inputText = 'test';
    $scope.posts = [
      'test test2;lksdf asdf one asdf poo',
      'arm test test2 asdf',
      'test head arm chest'
    ];

    $scope.myFilter = function(post) {
      // default to no match
      var isMatch = false;

      if ($scope.inputText) {
        // split the input by space
        var parts = $scope.inputText.split(' ');

        // iterate each of the words that was entered
        parts.forEach(function(part) {
          // if the word is found in the post, a set the flag to return it.
          if (new RegExp(part).test(post)) {
            isMatch = true;
          }
        });
      } else {
        // if nothing is entered, return all posts
        isMatch = true;
      }

      return isMatch;
    };
  }]);

这里是 plunkr:http://plnkr.co/edit/d17dZDrlhY2KIfWCbKyZ?p=preview

注意:此解决方案不将关键字限制为 3 个。可以输入任意数量的关键字,以 space 字符分隔。如果未输入任何内容(或仅输入 spaces),则所有内容都是 returned.