How do I show the results of a remote request in an Angular autocomplete material?

I am writing a website using angular material in which I am using autocomplete . Inside that autocomplete ( codepen here ) there is a function that returns search results from a local array of demo search items that (simplified) looks like this:

function querySearch (query) {
    var results = query ? self.repos.filter( createFilterFor(query) ) : self.repos, deferred;
    return results;
}

      

Now I want to edit this code so that I can query the server after each letter is entered. So I wrote angular code to request the server and return the promise as instructed here :

function querySearch (query) {
    return $http.get('/ajax/user/search/' + query).then(function(data){
        console.log(data); // I've got the data here. All fine.
        return data.data;
    });
}

      

Unfortunately, this doesn't work; the server receives the request for sure, but I see an empty offer list as you can see below:

enter image description here

Does anyone know how I can solve this problem? All advice is appreciated!

+3


source to share


2 answers


Look here for an example and click "simulate request" and disable request caching - https://material.angularjs.org/latest/#/demo/material.components.autocomplete

Just make sure you disable the cache md-no-cache="false"

if you really want it to fire every time and installmd-min-length="0"

You just want to replace the timeout they should mock the request with your actual request



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

      

And return your promise accordingly.

+2


source


One quick solution would be to simply return the function as:

function querySearch (query) {
    return $http.get('/ajax/user/search/' + query).success(function(data){
        console.log(data); // I've got the data here. All fine.
        return data.data;
    });
}

      

and then in the view change the call to:



md-items="item in ctrl.querySearch(ctrl.searchText)()"

      

so we execute the function you are returning now.

(Codepen for solution demonstration: http://codepen.io/anon/pen/qdyEBy )

0


source







All Articles