工厂与放大器之间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
}]);
问题是,我看到服务插座
已 MainCtrl
被注入,但里面的插座
服务,我无法访问 $ 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
?
有使用是事件的解决方法,但我不上太热衷。我已经成功尝试过,但我想preFER一个解决方案,这只是工作。
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.
推荐答案
您忘了注入 $范围
到您的控制器本身:
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该控制器的物,因为$范围inherhits $ rootScope,而不是周围的其他方式 - 因此你定义的 $范围
不会被传播到 $ rootScope
。
但是你可以做的是与你的工厂本身内varibale,所以像这样来链接 $ 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.
});
而在你的编程厂址:
And in your Socket-Factory:
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屋!