I am building an angularjs application, that has various controllers. For two of the controllers I am dependency injecting the same service. Is a separate instance of that service created for each of the controllers where it is being injected?
Asked
Active
Viewed 826 times
1

Pankaj Parkar
- 134,766
- 23
- 234
- 299

Sohan Shirodkar
- 510
- 3
- 24
-
ref. http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory – George Chen Mar 20 '16 at 16:41
1 Answers
5
Short Answer
From Docs
Lazily instantiated – Angular only instantiates a service/factory when an application component depends on it.
Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
Angular service/factory/provider
are Singleton object. Which create its instance only single time and if you ask for instance again(by injecting dependency) it gives back the old instance which was already created.
You could go throw this long answer which has everything explained

Community
- 1
- 1

Pankaj Parkar
- 134,766
- 23
- 234
- 299
-
Say, I have set a variable "cart" in myservice through controller1. Now I have injected myservice in cotroller2. Will I get the value of "cart" set before? – Sohan Shirodkar Mar 20 '16 at 17:24
-
1@SohanShirodkar yes.. that's how factory/service work.. they are singleton object. – Pankaj Parkar Mar 20 '16 at 17:26
-
@SohanShirodkar Yes.. see `service/factory/provider/value/constant`, they are just does something with some special meaning.. I don't think so you had went through the linked answer.. – Pankaj Parkar Mar 20 '16 at 17:29