javascript – AngularJS:使用共享服务(使用$resource)在控制器之间共享数据,但如何定义回调函数?

前端之家收集整理的这篇文章主要介绍了javascript – AngularJS:使用共享服务(使用$resource)在控制器之间共享数据,但如何定义回调函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
注意:我也在AngularJS邮件列表上发布了这个问题: https://groups.google.com/forum/#!topic/angular/UC8_pZsdn2U

大家好,

我正在构建我的第一个AngularJS应用程序,并且我不熟悉Javascript,所以任何指导都将非常感激:)

我的应用程序有两个控制器,ClientController和CountryController.在CountryController中,我正在从使用$resource对象的CountryService中检索国家列表.这很好,但我希望能够与ClientController共享国家/地区列表.经过一些研究,我读到我应该使用CountryService存储数据并将该服务注入两个控制器.

这是我以前的代码

CountryService:

  1. services.factory('CountryService',function($resource) {
  2. return $resource('http://localhost:port/restwrapper/client.json',{port: ':8080'});
  3. });

CountryController:

  1. //Get list of countries
  2. //inherently async query using deferred promise
  3. $scope.countries = CountryService.query(function(result){
  4. //preselected first entry as default
  5. $scope.selected.country = $scope.countries[0];
  6. });

在我改变后,他们看起来像这样:

CountryService:

  1. services.factory('CountryService',function($resource) {
  2. var countryService = {};
  3.  
  4. var data;
  5. var resource = $resource('http://localhost:port/restwrapper/country.json',{port: ':8080'});
  6.  
  7. var countries = function() {
  8. data = resource.query();
  9. return data;
  10. }
  11.  
  12. return {
  13. getCountries: function() {
  14. if(data) {
  15. console.log("returning cached data");
  16. return data;
  17. } else {
  18. console.log("getting countries from server");
  19. return countries();
  20. }
  21.  
  22. }
  23. };
  24. });

CountryController:

  1. $scope.countries = CountryService.getCountries(function(result){
  2. console.log("i need a callback function here...");
  3. });

问题是我曾经能够使用$resource.query()中的回调函数来预选默认选择,但是现在我已经将query()调用移到了我的CountryService中,我似乎已经失去了什么.

解决这个问题的最佳方法是什么?

谢谢你的帮助,
肖恩

解决方法

好吧……看起来我通过将回调函数一直传递给resource.query()调用解决问题.仍然不确定这是否是最好的方法.

作为参考,这是我做的:

CountryController:

  1. $scope.countries = CountryService.getCountries(function(){
  2. //preselected default
  3. $scope.selected.country = $scope.countries[0];
  4. });

CountryService:

  1. //Country Service. Will contain all relevant rest methods here
  2. services.factory('CountryService',{port: ':8080'});
  3.  
  4. var countries = function(callback) {
  5. data = resource.query(callback);
  6. return data;
  7. }
  8.  
  9.  
  10. return {
  11. getCountries: function(callback) {
  12. if(data) {
  13. console.log("returning cached data");
  14. return data;
  15. } else {
  16. console.log("getting countries from server");
  17. return countries(callback);
  18. }
  19.  
  20. }
  21. };
  22. });

猜你在找的JavaScript相关文章