【问题标题】:AngularJS search multiple keywords using one fieldAngularJS 使用一个字段搜索多个关键字
【发布时间】:2015-08-05 07:59:46
【问题描述】:

我是 AngularJS 的新手。我有 3 个输入字段可以为单个帖子输入最多 3 个关键字:

<input type="text" ng-model="Keyword1"></input>
<input type="text" ng-model="Keyword2"></input>
<input type="text" ng-model="Keyword3"></input>

我正在使用 ng-repeat 显示帖子:

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

并通过以下方式搜索:

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

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

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

谢谢!

【问题讨论】:

    标签: angularjs search angularjs-ng-repeat angular-ngmodel angular-filters


    【解决方案1】:

    不确定是返回与至少一个关键字匹配的所有帖子还是与所有关键字匹配的所有帖子。以下是如何创建自定义过滤器以匹配至少一个单词:

    <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 个。可以输入任意数量的关键字,以空格字符分隔。如果未输入任何内容(或仅输入空格),则返回所有内容。

    【讨论】:

    • 当它是键的对象时你怎么办?
    【解决方案2】:

    这就是我要做的事情

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

    【讨论】:

      猜你喜欢
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多