简体   繁体   中英

Implementing angular material autocomplete search on enter

I have made an auto complete which on clicking a button works well for fetching all the key results from the remote server. However the ask is to implement the same feature with the enter functionality on autocomplete bar.

Edit: The autosuggest is showing the result perfectly, I want to collect the search text and show the complete result on new page when user enters the search box else just the summary in autosuggest

navbar.html

...
    <div  ng-controller="AppCtrl as ctrl" >    
    <form ng-submit="$event.preventDefault()" style="width: 100%; background: transparent;" ng-controller="gotoSearchLanding">
                          <md-autocomplete
                              ng-disabled="ctrl.isDisabled"
                              md-no-cache="ctrl.noCache"
                              md-selected-item="ctrl.selectedItem"
                              md-search-text-change=""
                              md-search-text="ctrl.searchText"
                              md-selected-item-change="ctrl.selectedItemChange(item)"
                              md-items="item in ctrl.searchTextChange(ctrl.searchText)"
                              md-item-text="item.name"
                              md-min-length="0"
                              placeholder="Search Data"
                              ng-enter="gotoSearchLandingFun(ctrl.searchText)">>
                              <md-item-template>
                              <span class="item-title">
                                <img ng-src="img/jobs.png" width="20">
                                <span> {{item.name}} </span>
                              </span>
                              <span class="item-metadata">
                                <span class="item-metastat">
                                  <strong>{{item.employee_id}}</strong> 
                                </span>
                                <span class="item-metastat">
                                  <strong>{{item.email}}</strong> 
                                </span>
                              </span>
                            </md-item-template>
                          </md-autocomplete>
                        </form>
                        <span ng-controller="gotoSearchLanding">
                         <md-button class="md-fab md-mini" style="background-color:#fff" aria-label="Eat cake"  ng-click="gotoSearchLandingFun(ctrl.searchText)">
                            <ng-md-icon icon="search"></ng-md-icon>
                        </md-button>   
                        <span>
    </div>

controller.js

/**
 * Auto Search App Controller
 */

angular.module('AppTool')
  .controller('AppCtrl', [ '$http', '$state', AppCtrl]);
  function AppCtrl ($http, $state) {
    var self = this;      
    self.simulateQuery = false;
    self.isDisabled    = false;
    self.querySearch   = querySearch;
    self.selectedItemChange = selectedItemChange;
    self.searchTextChange   = searchTextChange;
    function querySearch (query) {
      var results = query ? self.repos.filter( createFilterFor(query) ) : self.repos,
          deferred;
      if (self.simulateQuery) {
        deferred = $q.defer();
        $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
        return deferred.promise;
      } else {

        return results;
      }
    }

    function searchTextChange(text) {
     return $http.get('http://localhost:3000/search', {
        params: {
          q: text
        }
      }).then(function(response){
        return response.data.map(function(item){
          return item._source;
        });
      }, function (error) {
          console.log("error");
      });
    }

    function selectedItemChange(item) {
    }

    function createFilterFor(query) {
      var lowercaseQuery = angular.lowercase(query);
      return function filterFn(item) {
        return (item.value.indexOf(lowercaseQuery) === 0);
      };
    }
}

gotsearchlandingCtrl.js

angular.module('AppTool')
    .controller('gotoSearchLanding', ['$scope','$state', gotoSearchLanding]);

function gotoSearchLanding($scope, $state) {

 $scope.gotoSearchLandingFun = function($val) {
        alert($val);  
        $state.go("searchLanding", { searchVal: $val});
    };     
}

directive.js

angular.module('PdbTool')
.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.myEnter);
                });
                event.preventDefault();
            }
        });
    };
});

Use your directive myEnter within the md-autocomplete tag.

Here is my modified code:

directives.myEnter = function () {
  return function (scope, element, attrs) {
      element.bind("keydown keypress", function (event) {
          if(event.which === 13) {
              scope.$apply(function () {
                  scope.gotoSearchLandingFun(scope.searchText);
              });
              event.preventDefault();
          }
      });
  };

}

and the autocomplete HTML:

<md-autocomplete  class="search_box"
                          md-selected-item="selectedItem"
                          md-search-text="searchText"
                          md-items="item in querySearch(searchText)"
                          md-search-text-change="querySearch(searchText)"
                          md-selected-item-change="search(searchText)"
                          md-item-text="item.value"
                          md-min-length="2"
                          md-autofocus="true"
                          md-no-cache="false"
                          placeholder="Search..." my-enter>
            <md-item-template>
                <span>{{item.value}}</span>
            </md-item-template>
            <md-not-found>
                No matches found.
            </md-not-found>
        </md-autocomplete>

Due to the myEnter scope is within the scope of your main functions, you can invoke them as you can see in the example.

You can have the Enter key select the item on form post if you use the following autocomplete properties:

md-require-match="true"
md-select-on-match="true"
md-match-case-insensitive="true"
md-selected-item="selectedItem"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM