I've been doing a lot of work on Angular.js
and overall I find it to be an interesting and powerful framework.
I know there have been a lot of discussions on Services vs. Factories vs. Providers vs. Values, but I am still pretty confused about what a Factory
is.
Factory has been defined in other StackOverflow discussions as the following:
Factories
Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.
I find this explanation to be very difficult to grasp and it doesn't increase my understanding of what a factory is.
Would anyone have any explanations or real life examples to share about what exactly a Factory
is and why you should use it in lieu of a Service
, Provider
, or other?
Update
A service
holds a reference to any object.
A factory
is a function which returns any object
A provider
is a function which returns any function
-phew-
My two cents on this topic. I am a very very newbie and just into understanding Angular JS and this was one of the things that confused me a lot and hence I studied it in somewhat detail. I have been making notes for giving interviews and this may be useful to others.
Services are mostly objects in which you describe the constructor class of the object. Somewhere deep within the framework, the Object.create() function is called and then you can use a service by calling its object and methods using a controller. Factory, on the other hand, doesn't create an object by default and hence requires you to return the entire object location once you're done defining all the attributes and methods.
One major difference I see is that you can run custom code in the factory. But, in a service, only object creation happens.
From what I understand they are all pretty much the same. The major differences are their complexities. Providers are configurable at runtime, factories are a little more robust, and services are the simplest form.
Check out this question AngularJS: Service vs provider vs factory
Also this gist may be helpful in understanding the subtle differences.
Source: https://groups.google.com/forum/#!topic/angular/hVrkvaHGOfc
jsFiddle: http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/
author: Pawel Kozlowski