javascriptangularjsautocompleteng-filter

Angular Search multiple input values


I have a result set populated via ng-repeat. Now I need to do a sort of filtering. I tried using ng-filter to filter out search results. Use Case : User can enter multiple merchantIds each comma separated(or any other preffered machanism). And the result set populated corresponds to the merchantIds the user entered. How currently works : Search works well when searching single merchantId. For example when user types merchantId, this list downs all merchants that starts with merchantId. When the input value is merchantId_1, the result is only related to merchantId_1. What I need is the user should be given the capability of typing merchantId_1, merchantId_2 (each comma seperated) and list down the result corresponds to both merchantIds.

What is the feasible way of achieving this using Angular.


Solution

  • I made a plunker that achieves what you were aiming for.

    https://plnkr.co/edit/T9Z6GCFHzwH9xCKxkxJ7?p=preview

    HTML:

    <input ng-model="searchText" />
    <div ng-repeat="merchant in merchants | merchantFilter:searchText">
      {{merchant}}
    </div>
    

    JS:

    angular.module('app', [])
    .controller('testController', function($scope) {
      $scope.merchants = ['merchant_1', 'merchant_2', 'merchant_3']
    })
    .filter('merchantFilter', function() {
      return function(merchants, searchText) {
        // If there's no input, return full list
        if (!searchText) return merchants;
        // Split and trim the search string
        var searchTerms = searchText.split(',');
        searchTerms = searchTerms.map(function(term) {
          return term.trim();
        })
        // Filter and return merchants matching any search term
        var returnedArray = [];
        _.forEach(merchants, function(merchant) {
          if (_.find(searchTerms, function(term) {
            return merchant.indexOf(term) > -1;
          })) {
            returnedArray.push(merchant)
          }
        })
        return returnedArray;
      }
    });