控制器之间Angularjs共享数据 [英] Angularjs sharing data between controllers
问题描述
我有一个从我的服务器获取某些客户端数据的服务:
I have a service that fetches some client data from my server:
app.factory('clientDataService', function ($http) {
var clientDataObject = {};
var cdsService = {
fetch: function (cid) {
//$http returns a promise, which has a then function, which also returns a promise
var promise = $http.get('/clients/stats/' + cid + '/').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
clientDataObject = {'data': response.data, 'currentClientID': cid};
return clientDataObject;
});
// Return the promise to the controller
return promise;
}
};
return cdsService;
});
然后在一个控制器中我做的:
Then in one controller I do:
//get stats
clientDataService.fetch($scope.id).then(function (response) {
$scope.client_data = {
'statistics': response.data
}
});
所有工作得很好。不过,我想从另一个控制器做一个手表上的服务,以更新它的数据改变时,甚则不必重新开球的http请求范围:
Which all works very well. However, I'm trying to do a watch from another controller on that service to update it's scope when the data changes, rather then having to re-kick off the http request:
$scope.$watch('clientDataService.clientDataObject', function (cid) {
alert(cid);
});
我只是提醒现在,但它永远不会触发。当页面加载最初,它会提醒不确定。我在控制台中没有错误,所有的$内喷射都很好,但它似乎永远不会承认,数据服务已经改变。我做得不对的手表?
I'm just alerting for now, but it never ever triggers. When the page initially loads, it alerts "undefined". I have no errors in the console and all the $injects are fine, but it never seems to recognize that data has changed in the service. Am I doing something wrong in the watch?
非常感谢
本
推荐答案
clientDataService.clientDataObject是不是你的控制器范围的一部分,所以你不能观看该对象上的变化。
您需要注入$ rootScope到您的服务,然后将更改广播到控制器的作用域。
clientDataService.clientDataObject is not part of your controller's scope, so you can't watch for changes on that object. You need to inject the $rootScope into your service then broadcast the changes to the controllers scopes.
app.factory('clientDataService', function ($rootScope, $http) {
var clientDataObject = {};
var cdsService = {
fetch: function (cid) {
var promise = $http.get('/clients/stats/' + cid + '/').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
clientDataObject = {'data': response.data, 'currentClientID': cid};
$rootScope.$broadcast('UPDATE_CLIENT_DATA', clientDataObject);
return clientDataObject;
});
// Return the promise to the controller
return promise;
}
};
return cdsService;
});
然后在控制器,你可以听使用的变化:
Then in the controller you can listen for the change using:
$scope.$on('UPDATE_CLIENT_DATA', function ( event, clientDataObject ) { });
这篇关于控制器之间Angularjs共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!