Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using $http in angular.js factory

Tags:

angularjs

In my app I am using angular.js and jquery ui autocomplete. I had the same problem that is discussed HERE The accepted answer there works great for me and is exactly what I needed up until today when I need to replace the static array of values with an $http ajax call. I tried to pass $http as parameter to the parent function but I get "Unknown provider: autoCompleteProvider <- autoComplete"

My question is, how can I use $http without rewriting or changing too much the current solution?

like image 260
baba-dev Avatar asked Dec 26 '12 20:12

baba-dev


1 Answers

You need to add a callback reference in your getSource() function of your service:

app.factory('autoCompleteDataService', ['$http', function($http) {
   return {
       getSource: function(callback) {
          var url = '...';
          $http.get(url).success(function(data) {
             callback(data);
          }
       }
   }
}]);

You could also use $http.jsonp, if your server returns json. Don't forget the JSON_CALLBACK parameter then.

In you directive you need to add the callback function itself:

...
autoCompleteDataService.getSource(function(data) {
   elem.autocomplete({
         source: data
         minLength: 2
   });    
});
like image 173
asgoth Avatar answered Sep 29 '22 01:09

asgoth