Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Angular Materialized Autocomplete With $http Service

DZone's Guide to

Angular Materialized Autocomplete With $http Service

Follow along with this tutorial to make your own travel application, that shows country or state of origin, and learn about the methods we'll call to make it work.

· Web Dev Zone
Free Resource

Never build auth again! Okta makes it simple to implement authentication, authorization, MFA and more in minutes. Try the free developer API today! 

This article is about Angular Materialized Autocomplete. The documentation for Angular Materialized is here. This documentation has a different version of Angular Materialized.

Things That You Can Try Out With AngularJS Material Autocomplete:

1) Simulate a Query.
2) Enable/Disable Caching.
3) Disable the Autocomplete on an Event.
4) Customization of a Listing Template.

Angular Materialized With $http Service:

The very first step is to set up the "ngMaterial" in your application. This is just some copy and
pasting where conditions apply.

Next, you need to inject the following dependencies into your Controller:

1) $timeout
2) $q
3) $log (Optional)
4) $http

Inject these dependencies as shown below: 

App.controller('MyController',["$scope","$http","$timeout","$q","$log",function($scope,$http,$timeout,$q,$log) {

}]); 

The rest of this article will address the methods you will need to call while working with Materialized Autocomplete.

querySearch()

The querySearch() method is the method you use to filter your query results with scope states. Hence, if simulateQuery returns false, querySearch() will execute theelse portion of our function. querySearch() achieves this by filtering the value with query parameters and scope.states that are called from the $http.

function querySearch (query) 
    {
        var results = query ? self.states.filter( createFilterFor(query) ) : self.states, // deferred;
        if (self.simulateQuery) 
            {
                deferred = $q.defer();
                 $timeout(function () { deferred.resolve( results ); 
            }, Math.random() * 1000, false);
             return deferred.promise;
          } else {
        return results;}
} 

createFilterFor()

This method allows you to create custom filters. In the example below, I have created a filter that returns query results that being with a lowercase letter.

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

function searchTextChange(text) {
        //This method call when input text changes.
function selectedItemChange(item) {
        //This method call when user select some value from the suggestions of the autocomplete.
}     

selected-item-change()

This method is the one which is also used to fetch data according to the source. A good example of this is the Country and State API. When your application needs to show suggestions for the user to select their country, which the State API can determine by taking the country ID.

loadAll()

function loadAll() {}  

This method consumes the data from the API and converts the data into searchable objects. Here is the updated loadAll() method.

function loadAll() {

    var url = "http://132.148.76.116:3000/api/sourceTransfer/";

    var sourcetransfer = [];

    $http.get(url)

        .success(function(data, status, headers, config) {

            $scope.sourceTransfer = data;

            angular.forEach($scope.sourceTransfer.data, function(value, key){

              var city = {display : value.sname, value : value.sname.toLowerCase() , sid : value.sid };
              sourcetransfer.push(city);

           });

        })

        .error(function(data, status, headers, config) {

          console.log("Error");

      });

    return  sourcetransfer;

    }
}

By fetching the data from the API, it's creating an array of objects that is used for comparing the value from the query. And, in the last line of code, I have returned the array.

This is the simplest way to load the array to Angular Materialized Autocomplete. You can also make the factory and inject it into the controller.

md-autocomplete Usage in an HTML Template

<md-autocomplete
  ng-disabled="ctrl.isDisabled"
  md-no-cache="ctrl.noCache"
  md-selected-item="ctrl.selectedItem"
  md-search-text-change="ctrl.searchTextChange(ctrl.searchText)"
  md-search-text="ctrl.searchText"
  md-selected-item-change="ctrl.selectedItemChange(item)"
  md-items="item in ctrl.querySearch(ctrl.searchText)"
  md-item-text="item.display"
  md-min-length="0"
  placeholder="What is your favorite US state?">
<md-item-template>
  <span md-highlight-text="ctrl.searchText" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
<md-not-found>
  No states matching "{{ctrl.searchText}}" were found.
  <a ng-click="ctrl.newState(ctrl.searchText)">Create a new one!</a>
</md-not-found>
 </md-autocomplete>


Screenshot: 

Image title

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
angular ,web dev ,methods ,functions

Published at DZone with permission of Puneet Sharma. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}