Reputation: 10703
I have been reading wrox angular book. Inside the book the author describes that a method of sharing data between controllers is to
as opposed to expose an object on a Service and letting angular's two way databinding do all the heavy lifting. Why would anyone go with the 'root scope publish/subscribe' methodology, instead of exposing an object on the service?
Upvotes: 6
Views: 2748
Reputation: 981
Say you have two controllers A and B, and a service S, storing the common data.
When A changes data in S, B cannot directly change its scope value by understanding that data in S has changed. Someone has to say to it that data in S has changed and update its scope according to this change. This may be done two ways.
Upvotes: 1
Reputation: 3062
That's interesting question.
First we should consider differences on various levels:
Scope
$rootScope
we define variable in global scopeExtensibility
$rootScope
- we have limited options to add additional logic to work on this value (we can define another global function)Encapsulation
$rootScope
- all object defined in $rootScope would be visible in all modulesModularity
$rootScope
- global variables is not places in module spacesMaintaining
$rootScope
- it's very hard to find which components use our $rootScope
variable. Binding
$rootScope
- it is easy to setup two-way binding in several controllers on one variable in $rootScope
In my opinion this is only useful for make really global variables.
Upvotes: 6
Reputation: 302
It depends which kind of data you are managing, if you are for example relying on a DB where you perform CRUD actions, you'd like a service to just interact with the DB.
That's called a stateless service, some people vouch for it and some are against and prefer to have state also on the service, exposing the object as you mentioned.
I'll leave you a couple resources with more information on the topic so you can decide which solution suits you best
http://www.johnpapa.net/sharing-data-in-an-angular-controller-or-an-angular-service/
http://www.webdeveasy.com/angularjs-data-model/
Upvotes: 0