注:この質問は、AngularJSメーリングリストにも投稿しました:https ://groups.google.com/forum/#!topic / angle / UC8_pZsdn2U
こんにちは、みんな、
私は最初のAngularJSアプリを作成していますが、そもそもJavascriptにあまり詳しくないので、ガイダンスをいただければ幸いです:)
私のアプリには、ClientControllerとCountryControllerの2つのコントローラーがあります。CountryControllerで、$resourceオブジェクトを使用するCountryServiceから国のリストを取得しています。これは問題なく機能しますが、国のリストをClientControllerと共有できるようにしたいと思います。調査の結果、CountryServiceを使用してデータを保存し、そのサービスを両方のコントローラーに挿入する必要があることを読みました。
これは私が以前持っていたコードでした:
CountryService:
services.factory('CountryService', function($resource) {
return $resource('http://localhost:port/restwrapper/client.json', {port: ':8080'});
});
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];
});
そして、私の変更後、それらは次のようになります。
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();
}
}
};
});
CountryController:
$scope.countries = CountryService.getCountries(function(result){
console.log("i need a callback function here...");
});
問題は、以前は$ resource.query()のコールバック関数を使用してデフォルトの選択を事前に選択できたのですが、countryService内にquery()呼び出しを移動したため、何が失われたように見えました。 。
この問題を解決するための最善の方法は何ですか?
助けてくれてありがとう、ショーン