Passing current scope to an AngularJS Service

S.C. picture S.C. · Mar 19, 2013 · Viewed 68.8k times · Source

Is it correct to pass the "current" $scope to an AngularJS service?

I'm in the situation where I've a $service knowing it's consumed by only one controller, and I'd like to have a reference to the controller's scope in the $service methods themselves.

Is this philosophically correct?

Or I'd better to broadcast events to the $rootScope and then make my controller listen to them?

Answer

Caio Cunha picture Caio Cunha · Mar 19, 2013

To let the controller know when something async happens, use Angular promises.

To provoke the $apply, you don't need the scope, you can call $rootScope.$apply, as there is no difference calling it in a specific scope or in the root.

Regarding the variable reading, it would be better if you received parameters. But you could also read it from a scope as an object parameter, but I would go with parameter, that would make your service interface much more clearer.