使用HTTP $在angular.js厂 [英] using $http in angular.js factory

查看:148
本文介绍了使用HTTP $在angular.js厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我使用angular.js和jQuery用户界面自动完成。我有这样的讨论同样的问题
<一href=\"http://stackoverflow.com/questions/12959516/problems-with-jquery-autocomplete-angularjs\">HERE
接受答案有伟大工程,对我来说,是正是我需要的,直到今天,当我需要用$ HTTP Ajax调用替换值的静态数组。
我试图通过HTTP $作为参数传递给父功能,但我得到未知提供商:autoCompleteProvider&LT; - 自动完成

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"

我的问题是,我该如何使用HTTP $无需重写或者改变太多当前的解决方案?

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

推荐答案

您需要在您添加的getSource回调引用()服务的功能:

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

您也可以使用 $ http.jsonp 的,如果你的服务器返回JSON。不要忘了JSON_CALLBACK参数即可。

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

这篇关于使用HTTP $在angular.js厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆