工厂与放大器之间AngularJS的数据共享;跨模块控制器

问题描述:

我有了几个模块的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.