Similarities between Services and factories in AngularJS – part2

In our previous post we looked at how to write service and factory and use it similarly by a uniform notation

I also showed how factory is a syntactic sugar on provider and service is a syntactic sugar on Factory.Once again all the code is hosted in this github repo

In our next section we will look at some other patterns.

1. We want a class based approach and we should be getting new instances from service/factory.Basically our requirement are objects that are unique to a constructor and which wont be shared like a singleton across the app .

factory('customFactoryThatReturnsAFunction', function () {

 var staticVariable = 1;

 function customFn(){
 console.log("custom Function is called")
 customFn.prototype.increment = function(){
 return ++this.value;
 return customFn

The factory returns a constructor function .The proper way to use this would be

var obj = new customFactoryThatReturnsAFunction();
 console.log("Increment value",obj.increment());

This above code is the best feature of a factory . the staticVariable behaves like a static variable and is shared across.This is the  exact reason you would want to user factory.


Can this be done using services ?

Yes it can be done ,but it will make the syntax messy and takes away the benefit of using services.



When should Services be used ?

  • When you have an constructor function,the instance of which needs to be single ton across the app.

When should factory be used ?

  • When you want to return an object that needs to be treated like a singleton
  • When you want to return a constructor function which will be used to construct new objects everytime.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s