What are the differences between a
Factory in AngularJS?
From the AngularJS mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. Compiling the answers:
Providers have the advantage that they can be configured during the module configuration phase.
See here for the provided code.
Here's a great further explanation by Misko:
In this case the injector simply returns the value as is. But what if you want to compute the value? Then use a factory
But what if you want to be more OO and have a class called Greeter?
Then to instantiate you would have to write
Then we could ask for 'greeter' in controller like this
But that is way too wordy. A shorter way to write this would be
But what if we wanted to configure the
Then we can do this:
As a side note,
I noticed something interesting when playing around with providers.
Visibility of injectables is different for providers than it is for services and factories. If you declare an AngularJS "constant" (for example,
But if you declare an AngularJS "value" (for example.,
" Hello world " example with
All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.
For me the best and the simplest way of understanding the difference is:
How AngularJS instantiates particular components (simplified):
So, for the service, what becomes the AngularJS component is the object instance of the class which is represented by service declaration function. For the factory, it is the result returned from the factory declaration function. The factory may behave the same as the service:
The simplest way of thinking is the following one:
The factory 'class' example is provided in the comments around, as well as provider difference.
The factory returns a function that can be invoked:
The factory can also return an object with a method that can be invoked:
The service returns an object with a method that can be invoked:
For more details, see a post I wrote on the difference: http://www.shanemkeller.com/tldr-services-vs-factories-in-angular/
Now whatever properties we attach to ‘service’ will be available to us when we pass ‘myFactory’ into our controller.
Now let’s add some ‘private’ variables to our callback function. These won’t be directly accessible from the controller, but we will eventually set up some getter/setter methods on ‘service’ to be able to alter these ‘private’ variables when needed.
Here you’ll notice we’re not attaching those variables/function to ‘service’. We’re simply creating them in order to either use or modify them later.
Now that our helper/private variables and function are in place, let’s add some properties to the ‘service’ object. Whatever we put on ‘service’ can be directly used inside whichever controller we pass ‘myFactory’ into.
We are going to create setArtist and getArtist methods that simply return or set the artist. We are also going to create a method that will call the iTunes API with our created URL. This method is going to return a promise that will fulfill once the data has come back from the iTunes API. If you haven’t had much experience using promises in AngularJS, I highly recommend doing a deep dive on them.
Below setArtist accepts an artist and allows you to set the artist. getArtist returns the artist. callItunes first calls makeUrl() in order to build the URL we’ll use with our $http request. Then it sets up a promise object, makes an $http request with our final url, then because $http returns a promise, we are able to call .success or .error after our request. We then resolve our promise with the iTunes data, or we reject it with a message saying ‘There was an error’.
Now our factory is complete. We are now able to inject ‘myFactory’ into any controller and we’ll then be able to call our methods that we attached to our service object (setArtist, getArtist, and callItunes).
In the controller above we’re injecting in the ‘myFactory’ service. We then set properties on our $scope object with data from ‘myFactory’. The only tricky code above is if you’ve never dealt with promises before. Because callItunes is returning a promise, we are able to use the .then() method and only set $scope.data.artistData once our promise is fulfilled with the iTunes data. You’ll notice our controller is very ‘thin’ (This is a good coding practise). All of our logic and persistent data is located in our service, not in our controller.
To really see the changes that occur when you invoke a function with the ‘new’ keyword, let’s create a function and invoke it with the ‘new’ keyword, then let’s show what the interpreter does when it sees the ‘new’ keyword. The end results will both be the same.
First let’s create our Constructor.
Now let’s add a method onto our Person’s prototype so it will be available on every instance of our Person ‘class’.
Now, because we put the sayName function on the prototype, every instance of Person will be able to call the sayName function in order alert that instance’s name.
Now that we have our Person constructor function and our sayName function on its prototype, let’s actually create an instance of Person then call the sayName function.
So all together the code for creating a Person constructor, adding a function to it’s prototype, creating a Person instance, and then calling the function on its prototype looks like this.
The biggest thing to understand when creating a Service is knowing that Services are instantiated with the ‘new’ keyword. Combining that knowledge with our examples above, you should now recognize that you’ll be attaching your properties and methods directly to ‘this’ which will then be returned from the Service itself. Let’s take a look at this in action.
Unlike what we originally did with the Factory example, we don’t need to create an object then return that object because, like mentioned many times before, we used the ‘new’ keyword so the interpreter will create that object, have it delegate to it’s prototype, then return it for us without us having to do the work.
First things first, let’s create our ‘private’ and helper function. This should look very familiar since we did the exact same thing with our factory. I won’t explain what each line does here because I did that in the factory example, if you’re confused, re-read the factory example.
Now, we’ll attach all of our methods that will be available in our controller to ‘this’.
Now just like in our factory, setArtist, getArtist, and callItunes will be available in whichever controller we pass myService into. Here’s the myService controller (which is almost exactly the same as our factory controller).
Like I mentioned before, once you really understand what ‘new’ does, Services are almost identical to factories in AngularJS.
The biggest thing to remember about Providers is that they’re the only service that you can pass into the app.config portion of your application. This is of huge importance if you’re needing to alter some portion of your service object before it’s available everywhere else in your application. Although very similar to Services/Factories, there are a few differences which we’ll discuss.
First we set up our Provider in a similar way we did with our Service and Factory. The variables below are our ‘private’ and helper function.
*Again if any portion of the above code is confusing, check out the Factory section where I explain what it all does it greater details.
You can think of Providers as having three sections. The first section is the ‘private’ variables/functions that will be modified/set later (shown above). The second section is the variables/functions that will be available in your app.config function and are therefore available to alter before they’re available anywhere else (also shown above). It’s important to note that those variables need to be attached to the ‘this’ keyword. In our example, only ‘thingFromConfig’ will be available to alter in the app.config. The third section (shown below) is all the variables/functions that will be available in your controller when you pass in the ‘myProvider’ service into that specific controller.
When creating a service with Provider, the only properties/methods that will be available in your controller are those properties/methods which are returned from the $get() function. The code below puts $get on ‘this’ (which we know will eventually be returned from that function). Now, that $get function returns all the methods/properties we want to be available in the controller. Here’s a code example.
Now the full Provider code looks like this
Now just like in our factory and Service, setArtist, getArtist, and callItunes will be available in whichever controller we pass myProvider into. Here’s the myProvider controller (which is almost exactly the same as our factory/Service controller).
As mentioned before, the whole point of creating a service with Provider is to be able to alter some variables through the app.config function before the final object is passed to the rest of the application. Let’s see an example of that.
Now you can see how ‘thingFromConfig’ is as empty string in our provider, but when that shows up in the DOM, it will be ‘This sentence was set…’.
My understanding is very simple below.
Factory: You simply create an object inside of the factory and return it.
You just have a standard function that uses this keyword to define a function.
There is a
Service vs provider vs factory:
First of all, let's talk about services in AngularJS!
So if there are three controller scope, let it be controllerA, controllerB and controllerC, all will share same service instance.
How to create a service?
AngularJS provide different methods to register a service. Here we will concentrate on three methods factory(..),service(..),provider(..);
We can define a factory function as below.
The passed function can define a object and return that object. AngularJS simply stores this object reference to a variable which is passed as first argument. Anything which is returned from fnFactory will be bound to serviceInstance . Instead of returning object , we can also return function, values etc, Whatever we will return , will be available to service instance.
It's the another way, we can register a service. The only difference is the way AngularJS tries to instantiate the service object. This time angular uses 'new' keyword and call the constructor function something like below.
In the constructor function we can use 'this' keyword for adding properties/methods to the service object. example:
Provider() function is the another way for creating services. Let we are interested to create a service which just display some greeting message to the user. But we also want to provide a functionality such that user can set their own greeting message. In technical terms we want to create configurable services. How can we do this ? There must be a way, so that app could pass their custom greeting messages and Angularjs would make it available to factory/constructor function which create our services instance. In such a case provider() function do the job. using provider() function we can create configurable services.
We can create configurable services using provider syntax as given below.
How does provider syntax internally work?
1.Provider object is created using constructor function we defined in our provider function.
2.The function we passed in app.config(), get executed. This is called config phase, and here we have a chance to customize our service.
3.Finally service instance is created by calling $get method of serviceProvider.
Sample code for creating service using provide syntax:
Factory use a factory function which return a service instance. serviceInstance = fnFactory();
Service use a constructor function and Angular invoke this constructor function using 'new' keyword for creating the service instance. serviceInstance = new fnServiceConstructor();
Provider defines a providerConstructor function, this providerConstructor function defines a factory function $get . Angular calls $get() to create the service object. Provider syntax has an added advantage of configuring the service object before it get instantiated. serviceInstance = $get();
You give AngularJS a function, AngularJS will cache and inject the return value when the factory is requested.
You give AngularJS a function, AngularJS will call new to instantiate it. It is the instance that AngularJS creates that will be cached and injected when the service is requested. Since new was used to instantiate the service, the keyword this is valid and refers to the instance.
You give AngularJS a function, and AngularJS will call its
Providers allow you to configure the provider before AngularJS calls the
Usage (as an injectable in a controller)
Usage (configuring the provider before
For me, the revelation came when I realized that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through dependency injection.
Say we have:
The difference between the three is that:
Which means there’s something like a cache object inside AngularJS, whose value of each injection is only assigned once, when they've been injected the first time, and where:
This is why we use
My clarification on this matter:
Basically all of the mentioned types (service, factory, provider, etc.) are just creating and configuring global variables (that are of course global to the entire application), just as old fashioned global variables were.
While global variables are not recommended, the real usage of these global variables is to provide dependency injection, by passing the variable to the relevant controller.
There are many levels of complications in creating the values for the "global variables":
Using as reference this page and the documentation (which seems to have greatly improved since the last time I looked), I put together the following real(-ish) world demo which uses 4 of the 5 flavours of provider; Value, Constant, Factory and full blown Provider.
Understanding AngularJS Factory, Service and Provider
All of these are used to share reusable singleton objects. It helps to share reusable code across your app/various components/modules.
A factory is function where you can manipulate/add logic before creating an object, then the newly created object gets returned.
It can be just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are injecting it inside your controller/factory/directive functions. It is instantiated only once per app.
Simply while looking at the services think about the array prototype. A service is a function which instantiates a new object using the 'new' keyword. You can add properties and functions to a service object by using the
Use it when you need to share a single object throughout the application. For example, authenticated user details, share-able methods/data, Utility functions etc.
A provider is used to create a configurable service object. You can configure the service setting from config function. It returns a value by using the
When you need to provide module-wise configuration for your service object before making it available, eg. suppose you want to set your API URL on basis of your Environment like
Hope this has cleared up your understanding about Factory, Service and Provider.
Factory: The factory you actually create an object inside of the factory and return it.
Here is some broilerplate code I've come up with as a code-template for object factory in AngularjS. I've used a Car/CarFactory as an example to illustrate. Makes for simple implementation code in the controller.
Here is a simpler example. I'm using a few third party libraries that expect a "Position" object exposing latitude and longitude, but via different object properties. I didn't want to hack the vendor code, so I adjusted the "Position" objects I was passing around.
I know a lot of excellent answer but I have to share my experience of using
This answer address the topic/question
how Factory, Service and Constant — are just syntactic sugar on top of a provider recipe?
how factory ,servic and providers are simailar internally
basically what happens is
When you make a
Source code of factory
When making a
Source code of service
So basically in both cases you eventually get a providers $get set to your function you provided , but you can give anything extra than $get as you can originally provide in provider() for config block
There are good answers already, but I just want to share this one.
First of all: Provider is the way/recipe to create a
And Value, Factory, Service and Constant (4 ways) - the syntactic sugar over Provider way/recepie.
Service is all about
And Factory is all about Factory Pattern - contains functions that return Objects like that Service.
And this simple/short video: covers also Provider: https://www.youtube.com/watch?v=HvTZbQ_hUZY (there you see can see how they go from factory to provider)
Provider recipe is used mostly in the app config, before the app has fully started/initialized.
This is very confusing part for newbie and I have tried to clarify it in easy words
AngularJS Service: is used for sharing utility functions with the service reference in the controller. Service is singleton in nature so for one service only one instance is created in the browser and the same reference is used throughout the page.
In the service, we create function names as property with this object.
AngularJS Factory: the purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object.
AngularJS Provider: the purpose of this is again same however Provider gives the output of it's $get function.
Defining and using Service, Factory and Provider are explained at http://www.dotnetfunda.com/articles/show/3156/difference-between-angularjs-service-factory-and-provider
As pointed out by several people here correctly a factory, provider, service, and even value and constant are versions of the same thing. You can dissect the more general
Here's the article this image is from:
Little late to the party. But I thought this is more helpful for who would like to learn (or have clarity) on developing Angular JS Custom Services using factory, service and provider methodologies.
I came across this video which explains clearly about factory, service and provider methodologies for developing AngularJS Custom Services:
Code posted here is copied straight from the above source, to benefit readers.
The code for "factory" based custom service is as follows (which goes with both sync and async versions along with calling http service):
The code for "service" methodology for Custom Services (this is pretty similar to 'factory', but different from syntax point of view):
The code for "provider" methodology for Custom Services (this is necessary, if you would like to develop service which could be configured):
Finally the UI which works with any of the above services:
Just to clarify things, from the AngularJS source, you can see a service just calls the factory function which in turn calls the provider function:
Syntactic Sugar is the difference. Only provider is needed. Or in other words only provider is the real angular, all other ones are derived(to reduce code). There is a simple version as well, called Value() which returns just the value, no calculation or function. Even Value is derived from provider!
So why such complications, why can't we just use provider and forget everything else? It is supposed to help us write code easily and communicate better. And toungue-in-cheek reply would be, the more complex it gets the better selling a framework will be.
Angular injection gives us the first hint in reaching this conclusion.
"$injector is used to retrieve object instances as defined by provider" not service, not factory but provider.
And a better answer would be this: "An Angular service is created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function."
So master provider and injector and all will fall in place :) . And it gets interesting in Typescript when $get can be implemented in a provider by inheriting from IServiceProvider.
Summary from Angular docs:
Best answers from SO:
1.Services are singleton objects that are created when necessary and are never cleaned up until the end of the application life-cycle (when the browser is closed). Controllers are destroyed and cleaned up when they are no longer needed.
2.The easiest way to create a service is by using the factory() method. The factory() method allows us to define a service by returning an object that contains service functions and service data. The service definition function is where we place our injectable services, such as $http and $q. Ex:
Using the factory() in our app
It’s easy to use the factory in our application as we can simply inject it where we need it at run-time.
Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course)
Features of Service:
First let's have a look at the syntax:
Now using the above two in the controller:
Features of Factory:
Let's again have a look at the Syntax first:
Features of Provider:
Essentially, Provider, Factory, and Service are all Services. A Factory is a special case of a Service when all you need is a $get() function, allowing you to write it with less code.
The major differences among Services, Factories, and Providers are their complexities. Services are the simplest form, Factories are a little more robust, and Providers are configurable at runtime.
Here is a summary of when to use each:
Factory: The value you are providing needs to be calculated based on other data.
Service: You are returning an object with methods.
Provider: You want to be able to configure, during the config phase, the object that is going to be created before it’s created. Use the Provider mostly in the app config, before the app has fully initialized.
After reading all these post It created more confuse for me.. But still all is worthfull information.. finally I found following table which will give information with simple comparision
And for beginner understand:- This may not correct use case but in high level this is what usecase for these three.
For basic scenarios factory&Service behaves same.
All the good answers already. I would like to add few more points on Service and Factory. Along with the difference between service/factory. And one can also have questions like:
Lets start with the difference between Service and factory:
A service is a constructor function, and Angular will instantiate it by calling new
Be careful with
Since the constructed service is an object, the methods inside it can refer to this when they’re called:
You might be tempted to call
Returning a Value from a
This means that you can basically copy-paste the factory example from below, replace
So when Angular constructs your service with new MyService(), it’ll get that api object instead of the MyService instance.
This is the behavior for any complex values (objects, functions) but not for primitive types.
A factory is a plain old function that returns a value. The return value is what gets injected into things that depend on the factory. A typical factory pattern in Angular is to return an object with functions as properties, like this:
Answers for above 1 and 2 questions: