我有一個通過REST檢索數據的服務。我想將結果數據存儲在服務級別變量中,以便在多個控制器中使用。當我將所有REST邏輯直接放入控制器時,一切正常,但當我嘗試將數據的檢索/存儲移動到服務中時,控制器在數據恢復時不會更新。我已經嘗試了很多不同的方式來維護服務和控制器之間的綁定。初始化AngularJS服務的工廠風格
控制器:
myApp.controller('SiteConfigCtrl', ['$scope', '$rootScope', '$route', 'SiteConfigService',
function ($scope, $rootScope, $route, SiteConfigService) {
$scope.init = function() {
console.log("SiteConfigCtrl init");
$scope.site = SiteConfigService.getConfig();
}
}
]);
服務:
myApp.factory('SiteConfigService', ['$http', '$rootScope', '$timeout', 'RESTService',
function ($http, $rootScope, $timeout, RESTService) {
var siteConfig = {} ;
RESTService.get("https://domain/incentiveconfig", function(data) {
siteConfig = data;
});
return {
getConfig:function() {
console.debug("SiteConfigService getConfig:");
console.debug(siteConfig);
return siteConfig;
}
};
}
]);
查看:
<div class="span4" ng-controller="SiteConfigCtrl">
<header>
<h2>
{{site.title}}
</h2>
</header>
可能是因爲您的服務已返回你的承諾,你必須在你的控制器使用「那麼」功能?詳情請看這裏。 http://johnmunsch.com/2013/07/17/angularjs-services-and-promises/ – javaCity
我想這就是問題所在。當服務異步檢索其數據時,如何動態地將控制器綁定到服務?我也只想進行一次REST調用,並在檢索後使用會話的本地副本。 – wisemanIV