2

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. }); 

And then I have;

var apiService = angular.module('apiService', ['ngResource']); // etc 

and;

apiService.factory('Socket', ['$rootScope', function ($rootScope) { // create a websocket and listen for stuff // if something happens, update 'objects' in $rootScope }]); 

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.

2
  • Where is the code that assigns the objects to $rootScope? Commented Mar 19, 2014 at 16:22
  • My assumption is that $scope from MainCtrl can be referred to (somehow) from the Socket factory. So, quite obviously, the use of $rootScope would be wrong. So to refine the question, I'd like a replacement for $rootScope in Socket so that I refer to the scope Socket was injected into. Commented Mar 19, 2014 at 16:26

1 Answer 1

3

You forgot to inject the $scope into your controller itself:

app.controller('MainCtrl', function ($scope, Socket) { $scope.objects = {}; // do something with $scope.objects, etc. }); 

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.

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 : {} } }]); 

Just be careful then to not overwrite the $scope.objects directly, since it will break the reference again.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.