Javascript 使用服务AngularJS在两个控制器之间共享动态数据
我有两个angular服务需要共享模型(一个消息列表和一个单独的消息),它们是通过调用我们的API获得的。服务内容如下:Javascript 使用服务AngularJS在两个控制器之间共享动态数据,javascript,rest,angularjs,controller,Javascript,Rest,Angularjs,Controller,我有两个angular服务需要共享模型(一个消息列表和一个单独的消息),它们是通过调用我们的API获得的。服务内容如下: angular.module('CmServices', ['ngResource']) .factory('Messages', function ($resource, $routeParams, $rootScope) { var data = {}; data.rest = $resource(url, {}, { que
angular.module('CmServices', ['ngResource'])
.factory('Messages', function ($resource, $routeParams, $rootScope) {
var data = {};
data.rest = $resource(url, {}, {
query: {method:'GET', params: params},
post: {method:'POST', params: params}
});
// Trying to set this through a call to the API (needs to get param from route)
$rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
var messages = data.rest.query({m_gid: $routeParams.gid}, function () {
data.messages = messages;
});
});
return data;
});
控制器为:
function MessagesCtrl ($scope, $http, $location, $routeParams, Messages) {
$scope.messages = Messages.messages;
}
function MessageCtrl ($scope, $http, $location, $routeParams, Messages) {
$scope.messages = Messages.messages[0];
}
但是当从REST API加载数据时,这两个控制器都不会更新(我已经记录了返回的数据,它肯定会更新)。问题在于,您正在向每个控制器返回不同版本的
数据。我会将消息
放在$rootScope中。所以
data.rest.query({m_gid: $routeParams.gid}, function () {
$rootScope.messages = messages;
});
顺便问一下,将data.rest.query
的返回值设置为var messages
的目的是什么?当您离开函数时,该变量将被吹扫。而不是将新数组分配给数据。消息如下所示:
data.messages = messages
改为使用,它将填充相同的数组:
angular.copy(messages, data.messages)
这样,控制器将看到更新