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