1
我在寻找一个更好的办法来做到以下几点:更新从多个控制器服务的变量
我有这个服务:
dashboardApp.service('MessagesService', function() {
var message = "";
this.update = function (new_message) {
message = new_message;
};
this.get = function() {
return message;
}
});
,让我们说我有这个控制器:
dashboardApp.controller('GroupPageController', function($scope, MessagesController){
$scope.message = MessagesController.get();
})
是$ scope.message变量是在我的HTML页面:
<h3 ng-bind="message"></h3>
,让我们说我有这个第二控制器:
dashboardApp.controller('ChangeController', function($scope, MessagesController, $http){
$scope.sendEmail = function() {
$http({
method: "post",
url: "/enterprises/vouchers/_send",
data: {
group_id: group_id,
group_student_ids: group_student_ids
}
}).success(function (response) {
MessagesService.update(response.message);
}).error(function() {
console.log("failed")
});
}
})
所以在这里,点击一些按钮时,这个功能从Web API获取数据并更新服务中的变量。然后,我期望第一个控制器中的$ scope.message变量也进行更新,这样HTML页面也会改变。但是这并没有发生。所以,我使用$手表:
$scope.$watch(function() {
return MessagesService.get();
}, function (newValue, oldValue) {
if (newValue !== oldValue) {
$scope.message = MessagesService.get();
}
});
然后,一切正常,因为我希望它。但我读过一些文章,据说不应该在控制器内部使用$ watch。
如何在没有$ watch的情况下实现此功能?
其优良的使用$看你的控制器内。 – alsco77 2014-12-19 09:58:06
@ alsco77,真的吗?这是好消息)[这里](http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html)是我提到的链接,其中说“DON” T使用$ watch在控制器“ – Rodrigue 2014-12-19 10:01:00
据我所见,他似乎只能看范围变量,而不是从外部服务 – alsco77 2014-12-19 10:06:00