AngularJS 在工厂和工厂之间共享数据跨模块控制器 [英] AngularJS sharing data between factory & controller across modules
问题描述
我有一个包含多个模块的 angularjs 应用程序.主要模块看起来像:
I have an angularjs app that has several modules. The main modules looks something like:
var app = angular.module('mainMod', ['apiService']);
app.controller('MainCtrl', function (Socket) {
$scope.objects = {};
// do something with $scope.objects, etc.
});
然后我有;
var apiService = angular.module('apiService', ['ngResource']); // etc
和;
apiService.factory('Socket', ['$rootScope', function ($rootScope) {
// create a websocket and listen for stuff
// if something happens, update 'objects' in $rootScope
}]);
问题是,我看到服务Socket
已经注入到MainCtrl
中了,但是在Socket
服务里面,却无法访问$rootScope.objects
.我确实理解工厂没有自己的范围,但是由于它被注入到 MainCtrl
中,所以 rootscope 不应该引用 MainCtrl
的范围吗?
The thing is, I see that the service Socket
has been injected in MainCtrl
, but inside the Socket
service, I can not access $rootScope.objects
. I do understand that factories have no scopes of their own, but since its injected into MainCtrl
, shouldn't the rootscope refer to the scope of the MainCtrl
?
有一种使用事件的解决方法,但我不太热衷于此.我已经成功尝试过,但我更喜欢这样的解决方案.
There is a workaround using events, but I'm not too keen on that. I have tried it with success but I'd prefer a solution where this just works.
推荐答案
您忘记将 $scope
注入控制器本身:
You forgot to inject the $scope
into your controller itself:
app.controller('MainCtrl', function ($scope, Socket) {
$scope.objects = {};
// do something with $scope.objects, etc.
});
但是这仍然不会帮助您通过 rootScope 访问该控制器的对象",因为 $scope 继承了 $rootScope,但不是相反的 - 所以无论您在 $scope<上定义什么/code> 不会传播到
$rootScope
.
But this still won´t help you to access the "objects" of this controller via the rootScope, since $scope inherhits $rootScope, but not the other way around - so whatever you define on the $scope
wont be propagated to the $rootScope
.
然而,您可以做的是将 $scope.objects
与工厂内部的变量链接起来,如下所示:
What you CAN do however is to link the $scope.objects
with a varibale inside your factory itself, so something like this:
var app = angular.module('mainMod', ['apiService']);
app.controller('MainCtrl', function (Socket) {
$scope.objects = Socket.objects = {};
// do something with $scope.objects, etc.
});
在您的套接字工厂中:
apiService.factory('Socket', ['$rootScope', function ($rootScope) {
return {
objects : {}
}
}]);
注意不要直接覆盖$scope.objects
,因为它会再次破坏引用.
Just be careful then to not overwrite the $scope.objects
directly, since it will break the reference again.
这篇关于AngularJS 在工厂和工厂之间共享数据跨模块控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!