Our Engineers can Write as well

Implementing md-autocomplete with Angularjs

AngularJS is a JavaScript-based open-source front-end web application framework that is incredibly popular among developers as it provides an excellent toolset to build an application most dynamically with rich interactive features and functionalities for a real-time experience. Mostly used in Single Page Application (SPA) projects, AngularJS models are plain old JavaScript objects which makes it easy to code, test, maintain reuse and again free from boilerplate.

In this blog by Future Focus, let’s understand one of the main input – component of AngularJs, “md-autocomplete” and how it is implemented during development.

Introduction:

Md-autocomplete is a framework which is used to display content based on what we type in the search field. With md-autocomplete, you will be able to pick content from the drop-down that would have all the possible matches as it would predict the word when we type in letters. Md-autocomplete is different from the usual autocomplete that we use in our day-to-day life. Md-autocomplete will allow you to key in any value but will not allow you to select a value which is not part of the drop-down. Browser cache will not be reflected in the drop-down.

Please find a sample drop down of a web application meant for employee vehicle bookings where Md-autocomplete is used.

implementing md autocomplete with angularjs
Steps to Implement:

1. Include required JS files:

  • a. angular.min.js

  • b. angular-animate.min.js

  • c. angular-aria.min.js

  • d. angular-messages.min.js

  • e. angular-material.min.js

(1) angular.min.js: This file is best used to deploy an application as it reduces the loading time of a web page.

(2) angular -animate.min.js: This file contains the angularjs animation library which is added to make use of ngAnimate attribute.

(3) angular -aria.min.js: This file is added to make use of ngAria attribute. ARIA stands for Accessible Rich Internet Application which provides more accessibility to users of assistive technologies such as interactive white boards and handheld audio reader.

(4) angular -messages.min.js: This file to added to make use of ngMessages attribute which listens to a key/value object and based on its state shows or hides a message.

(5) angular -material.min.js: This file contains UI component library for angularjs which can be reused to help in developing web pages that are attractive, consistent and browser portable.

2. Inject [‘ngMaterial’] into angular application:

angular

            .module(‘appName’, [‘ngMaterial’])

3. Include <md-autocomplete> within a form at any required location

Code Below:

 <md-autocomplete  class=”autocomp”  flex=””  class=”passengerValue”  md-selected-item=”selectedItem[$index]”  md-input-minlength=”2″  md-input-maxlength=”30″  md-no-cache=”ctrl.noCache”  md-search-text=”ctrl.searchText”  md-items=”item in ctrl.querySearch(ctrl.searchText)”  placeholder=””  md-item-text=”item.display”  md-search-text-change=”ctrl.searchTextChange(ctrl.searchText)”  md-selected-item-change=”storeVehicleRequestName()” md-floating-label=”Select an Employee”>

            <md-item-template>                                                                         

                                                 <span md-select-on-focus>

                                                        {{item.display}}

                                               </span>                                                            

                                  </md-item-template>

          </md-autocomplete>

Attributes:

The below mentioned table lists some of the frequently used attributes and their description.

SNoNameDescription
1.md-items (required)Iterates over the matches for your search.
2.md-selected-itemAn object(model) that is used to bind the selected item to.
3.md-input-minlengthHolds the minimum length of input value used for validation
4.md-input-maxlengthHolds the maximum length of input value used for validation.
5.md-no-cacheDisables cache that happens internally when autocomplete is used.
6.md-search-textA model that is used to bind the search query to the text to be searched
7.md-item-textUsed to convert object to a single string
8.md-search-text-changeAn expression to be run each time the search text updates.
9.md-selected-item-changeThis attribute is called each time when the text (to be searched) is updated.
10.md-floating-labelA string that will add a floating label to autocomplete and wrap it in md-input-container.

4. Include <md-item-template> to set the required display format:

Code Below:

<md-item-template>

                   <span md-select-on-focus>{{item.display}}</span>

</md-item-template>

5. Load search and display contents into scope:

Depending on the input given by the user, the data is fetched from the database.

Code Below:

function querySearch(query) {

                var results = query ? self.states.filter (createFilterFor (query)): self.states;

                if (self.simulateQuery) {

                    var deferred = $q.defer();

                    $timeout(function() {

                        deferred.resolve(results);

                    }, Math.random() * 1000, false);

                    return deferred.promise;

                } else {

                    return results;

                }

            }

6. Include search function:

When the user types in the input (whether in Upper case or Lower case), this function converts the first letter of the word to be searched into Upper case.

Code Below:

function searchTextChange(text) {

                var uppercase = text.toUpperCase();

                if (text !== uppercase) {

                    self.searchText = uppercase;

                }

            }

Example and sample code:
index.html:

Code Below:

<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js”></script>

<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js”></script>

<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js”></script>

<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js”></script>

<script src = “https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js”></script>

app.js:

Code Below:

angular

            .module(‘firstApplication’, [‘ngMaterial’])

            .controller(‘autoCompleteController’, autoCompleteController);

View:

Code Below:

<md-autocomplete   class=”autocomp”  flex=””   class=”passengerValue”   md-selected-item=”selectedItem[$index]”   md-input-minlength=”2″   md-input-maxlength=”100″  md-no-cache=”ctrl.noCache”   md-search-text=”ctrl.searchText”  md-items=”item in ctrl.querySearch(ctrl.searchText)”   ng-enter=”acceptEnterButton(ctrl.searchText)”  placeholder=””  md-item-text=”item.display”                      md-search-text-change=”ctrl.searchTextChange(ctrl.searchText)”  md-selected-item-change=”storeVehicleRequestName()”   md-floating-label = “Select an Employee”>                             

                           <md-item-template>                                                                         

                                                 <span md-select-on-focus>

                     {{item.display}}

                                                 </span>                                                            

                                  </md-item-template>

          </md-autocomplete>

Controller:

Code Below:

function querySearch(query) {

    var results = query ? self.states.filter (createFilterFor (query)): self.states;

          if (self.simulateQuery) {

                                   var deferred = $q.defer();

                    $timeout(function() {

                        deferred.resolve(results);

                    }, Math.random() * 1000, false);

                    return deferred.promise;

                } else {

                    return results;

                }

            }

function searchTextChange(text) {

                var uppercase = text.toUpperCase();

                if (text !== uppercase) {

                    self.searchText = uppercase;

                }  }

We trust that this blog helps you in understanding the way md-autocomplete is implemented with AngularJs.

For more such quick and useful development tips, keep watching this space.

Menaka - Software Engineer

Contributed by:

Menaka
Software Engineer

Your email address will not be published. Required fields are marked *