【发布时间】:2013-11-07 20:53:46
【问题描述】:
我有一个通过 REST 检索数据的服务。我想将结果数据存储在服务级别变量中,以便在多个控制器中使用。当我将所有 REST 逻辑直接放入控制器时,一切正常,但是当我尝试将数据的检索/存储移动到服务中时,当数据返回时控制器不会被更新。我尝试了很多不同的方法来维护服务和控制器之间的绑定。
控制器:
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>
【问题讨论】:
-
可能是因为您的服务正在向您返回一个承诺,而您必须在控制器中使用“then”函数?有关更多详细信息,请参见此处。 johnmunsch.com/2013/07/17/angularjs-services-and-promises
-
我想这就是问题所在。当服务异步检索其数据时,如何将控制器动态绑定到服务?我也只想进行一次 REST 调用,并在检索到会话后使用本地副本。
标签: angularjs angularjs-service angularjs-controller