How to apply Angular Material autocomplete search functionality triggered by pressing the "Enter"

I have created an auto-complete feature that, upon clicking a button, successfully retrieves all key results from a remote server. However, there is a request to implement the same functionality using the enter key on the auto-complete bar.

Edit: The auto-suggest feature displays the results perfectly. I want to capture the search text and display the complete results on a new page when the user enters the search box. Otherwise, only show a summary in the auto-suggest dropdown.

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

Answer №1

Utilize the myEnter directive inside the md-autocomplete tag.

Below is the updated 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>

Since the myEnter scope is nested within your main functions' scope, you can call them as shown in the example.

Answer №2

If you want the form to automatically select an item when the Enter key is pressed, make sure to include these autocomplete properties:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Django AJAX call for data retrieval

Can someone assist me, please? I'm trying to update content on a page without refreshing when a button is clicked. Currently, my approach involves using the jQuery cookie plugin to save the button's id into a cookie and then reading that value in ...

There is no information available at this time

Currently, I am delving into Angular and am keen on creating a web application that consumes a Restful Web service. The setup of my page is as follows: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html ng-app="Tri ...

Regain focus when clicking outside of md-chips

Since updating Angular Material from version 1.1.1 to 1.1.4, I've noticed that the md-chips are not functioning as they used to. When I enter a string and click outside, the focus goes back to the input field, which is not what I want. This behavior ...

Assigning a value to a variable can prevent the occurrence of an

My recursive code consists of two pieces aiming to print out half of the array recursively until we reach arrays of length 1. Surprisingly, the code without variable assignment runs infinitely, while the code with variable assignment behaves as expected. ...

Maintain current page with HTML form action

I am currently working on a newsletter signup form located in the footer of every page on my website. When a user enters their email and clicks submit, the form takes them to "newsletter.php" which then sends me an email with their information. However, I ...

Is it possible to obtain the impending exception handling protocol in advance?

In upcoming scenarios, unhandled promise rejections will lead to the termination of the Node.js process using a non-zero exit code. Despite encountering issues, my pipeline erroneously passed and deployed a faulty version that crashes upon launch. If Node ...

Is there a way to integrate the AJAX response from JavaScript into a JavaScript function?

I am having a nightmare trying to solve this issue. I am currently working on an app using phonegap and have integrated highcharts for creating graphs. The graph displays properly, but the tooltip is not working as expected. Below is the code snippet that ...

I'm having trouble showing the concealed list with JavaScript

I am new to javascript and facing a challenge. Whenever I update the list items in an HTML example from engineer, pilot, technician, if I select engineer, there should be an onchange event calling a function in JavaScript that shows a hidden select list co ...

Mastering the art of debugging a mongoose action in node.js

I am utilizing mongoose for connecting my node.js app with mongoDB. However, I am facing an issue where the database does not get updated when I create or update a model instance. How can I effectively debug and identify what goes wrong in the create or up ...

Back from the depths of the .filter method encased within the .forEach

I have been working on this code and trying to figure it out through trial and error: let _fk = this.selectedIaReportDiscussedTopic$ .map((discussionTopic) => {return discussionTopic.fk_surveyanswer}) .forEach((fk) => { ...

Unable to retrieve array information within a reactjs environment

I encountered an issue while trying to retrieve data from the getObjectives function as it returned undefined. I am unsure whether the problem lies within the function itself or in the code implementation. Here is the GetObjectives() function: export asyn ...

What is the best way to determine the duration it takes for a perspective camera to move from one position to another

As my perspective camera moves along a spline curve, I need to determine the amount of time it has traveled. I have already calculated the total distance covered. What should be my next step? ...

Angular service for making HTTP requests

service creation myApp.factory('customService', ['$http', function(http) { http.get($scope.url).then(function(result){ customVariable = result; } return customVariable; } Controller function appCtrl($scope, customService){ ...

Is it possible to implement a while loop in React?

Issue: I am facing a challenge while attempting to generate an array of 4 elements from a list using a while loop, but it seems to result in an infinite loop. const [options, setOptions] = useState([]); const fetchElements = () => { while(options. ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

Display the next dropdown menu after selecting an option from the first dropdown using a JQuery

Looking to dynamically update my second drop-down list from the database based on the selection made in the first drop-down list within a jQuery dialog. ASPX <asp:UpdatePanel ID="upnl" OnLoad="upnl_Load" runat="server" UpdateMode="Conditional"> < ...

Utilizing Discord.js to enable a command for a particular channel

Running a Discord.js bot and struggling to figure out how to restrict the command! help to only the #commands channel. Already have the channel ID, so what steps should be taken in the command event to achieve this? Appreciate any guidance! ...

Challenge yourself with the act of dragging and dropping multiple times using only Javascript

I'm currently working on implementing a drag and drop functionality from one column to another. The goal is to allow multiple copies of an element from the left list to be placed in the right list. Each copy will have a unique ID assigned before being ...

I encounter difficulty utilizing assets within my React application

Currently, I am in the process of developing a React application for practice purposes. However, I have encountered an issue with using images and audio files stored in the assets folder. Despite my attempts to import them into the project, I have been uns ...

Auto-updating Angular $scope variables

I am facing an issue with two variables in my code. Whenever I update one variable, the other variable also gets updated automatically. Can someone please help me understand what is causing this behavior? $scope.pages = []; $scope.pagesSave = []; var fun ...