using $http in angular.js factory

前端 未结 2 1814
长情又很酷
长情又很酷 2021-02-10 03:08

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 nee

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-10 03:39

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

提交回复
热议问题