Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing current scope to an AngularJS Service

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?

like image 929
S.C. Avatar asked Mar 19 '13 20:03

S.C.


People also ask

Does AngularJS support scope inheritance?

The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes.

What is the number of scopes allowed in an AngularJS application?

Each AngularJS application has exactly one root scope, but may have any number of child scopes.

What is scope in AngularJS with example?

AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.

What is scope apply in AngularJS?

The $scope. $apply() function is used to execute some code, and then call $scope. $digest() after that, so all watches are checked and the corresponding watch listener functions are called. The $apply() function is useful when integrating AngularJS with other code.


1 Answers

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.

like image 187
Caio Cunha Avatar answered Sep 22 '22 19:09

Caio Cunha