Search code examples
angularjssearchangularjs-ng-repeatangular-ngmodelangular-filters

AngularJS search multiple keywords using one field


I am new to AngularJS. I have 3 input fields to enter up to 3 keywords for a single post:

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

I am displaying the posts using ng-repeat:

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

and searching by:

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

As you can see, this currently only searches the first keyword of every post. How can I have only one search field that searches all three keywords of a post? I know I cannot just do

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

Thanks!


Solution

  • Not sure if the intention is to return all posts that match at least one keyword or all posts that match all keywords. Here is how you could create a custom filter for matching at least one word:

    <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;
        };
      }]);
    

    And here is the plunkr: http://plnkr.co/edit/d17dZDrlhY2KIfWCbKyZ?p=preview

    NOTE: this solution does not limit the keywords to 3. Any number of keywords can be entered, separate by the space character. If nothing is entered (or just spaces), everything is returned.