sha*_*lim 7 javascript angularjs
注意:我还在AngularJS邮件列表上发布了这个问题:https://groups.google.com/forum/#!topic / angular/UUC8_pZsdn2U
大家好,
我正在构建我的第一个AngularJS应用程序,并且我不熟悉Javascript,所以任何指导都将非常感谢:)
我的应用程序有两个控制器,ClientController和CountryController.在CountryController中,我正在从使用$ resource对象的CountryService中检索国家列表.这很好,但我希望能够与ClientController共享国家/地区列表.经过一些研究,我读到我应该使用CountryService来存储数据并将该服务注入两个控制器.
这是我以前的代码:
CountryService:
services.factory('CountryService', function($resource) {
return $resource('http://localhost:port/restwrapper/client.json', {port: ':8080'});
});
Run Code Online (Sandbox Code Playgroud)
CountryController:
//Get list of countries
//inherently async query using deferred promise
$scope.countries = CountryService.query(function(result){
//preselected first entry as default
$scope.selected.country = $scope.countries[0];
});
Run Code Online (Sandbox Code Playgroud)
在我改变之后,它们看起来像这样:
CountryService:
services.factory('CountryService', function($resource) {
var countryService = {};
var data;
var resource = $resource('http://localhost:port/restwrapper/country.json', {port: ':8080'});
var countries = function() {
data = resource.query();
return data;
}
return {
getCountries: function() {
if(data) {
console.log("returning cached data");
return data;
} else {
console.log("getting countries from server");
return countries();
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
CountryController:
$scope.countries = CountryService.getCountries(function(result){
console.log("i need a callback function here...");
});
Run Code Online (Sandbox Code Playgroud)
问题是我以前能够使用$ resource.query()中的回调函数来预选默认选择,但是现在我已经将query()调用移到了我的CountryService中,我似乎已经失去了什么.
解决这个问题的最佳方法是什么?
谢谢你的帮助,肖恩
好吧..看来我通过将回调函数一直传递到resource.query() 调用来解决了这个问题。仍然不确定这是否是最好的方法。
作为参考,这就是我所做的:
国家控制器:
$scope.countries = CountryService.getCountries(function(){
//preselected default
$scope.selected.country = $scope.countries[0];
});
Run Code Online (Sandbox Code Playgroud)
国家/地区服务:
//Country Service. Will contain all relevant rest methods here
services.factory('CountryService', function($resource) {
var countryService = {};
var data;
var resource = $resource('http://localhost:port/restwrapper/country.json', {port: ':8080'});
var countries = function(callback) {
data = resource.query(callback);
return data;
}
return {
getCountries: function(callback) {
if(data) {
console.log("returning cached data");
return data;
} else {
console.log("getting countries from server");
return countries(callback);
}
}
};
});
Run Code Online (Sandbox Code Playgroud)