1

I am new to Angular and trying to clear my concepts:

My app requires a single model which will be updated by different controllers. So, the model should be shared. Following link explains clearly how should I proceed with it

http://www.webdeveasy.com/angularjs-data-model/

It creates two services using factory method. The manager service checks whether the model class has been already instantiated or not. If yes it returns an already instantiated reference otherwise it new's an instance. Hence each model sees the same model instance and on updating model updates occur in all the views.

If instead of creating service using factory, one creates a service using service method which returns a new'd instance automatically, would that be shared or bound to the controller.

I assume my case cannot be achieved using service method, i must use factory method instead of service method as it new's the services everytime it is injected in any controller. Does angular not maintain some pool internally to make sure same service instance is injected in all the controllers.

I don't want an additional manager object for the model to ensure same instance being used in all the controllers

adnan kamili
  • 7,575
  • 5
  • 50
  • 105

1 Answers1

4

As far as your case is concerned, Both services and factory can be used, as both of them are essentially similar in nature by functionalities.

As per my understanding, you want a single news entity, to be shared across all controllers, as per singleton design pattern, ensuring one update -> updates all. This can be perfectly implemented using Angular Services.

I myself find using services easier than factory method, since the former has an easy to use syntax :D

Also, for more understanding of Difference between the two approaches, you can have a look at this answer

enter image description here

Community
  • 1
  • 1
Manish Kr. Shukla
  • 4,357
  • 1
  • 16
  • 33
  • Also check the following thread : http://stackoverflow.com/questions/13762228/confused-about-service-vs-factory/13763886#13763886 and http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory/15666049#15666049 – kwangsa May 21 '15 at 05:53
  • @TechMa9iac Everytime a class is newed it creates a separate instance, services are newed automatically, that won't allow for sharing the instance. I can't keep track of instances in service method to share them across controllers but in factory I can – adnan kamili May 21 '15 at 05:53
  • They won't be **newed**. You will have the same instance shared across all the controllers and other app components. Implement it programmatically .. – Manish Kr. Shukla May 21 '15 at 05:58
  • @TechMa9iac I don't have any "news" entity by new's i meant javascript new keyword – adnan kamili May 21 '15 at 05:59
  • I understand.. Give it a try.. Services will work, there won't be any new instances, the same will be shared all across. – Manish Kr. Shukla May 21 '15 at 06:56