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);
});
我现在只是提醒,但它永远不会触发.当页面最初加载时,它会警告未定义".我在控制台中没有错误,所有 $injects 都很好,但它似乎从未意识到服务中的数据已更改.我在手表上做错了什么吗?
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屋!