AngularJS : When to use service instead of factory

Explanation

You got different things here:

First:

  • If you use a service you will get the instance of a function (“this
    keyword).
  • If you use a factory you will get the value that is returned by
    invoking the function reference
    (the return statement in factory).

ref: angular.service vs angular.factory

Second:

Keep in mind all providers in AngularJS (value, constant, services, factories) are singletons!

Third:

Using one or the other (service or factory) is about code style.
But, the common way in AngularJS is to use factory.

Why ?

Because “The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. Since factories are regular functions, we can also take advantage of a new lexical scope to simulate “private” variables. This is very useful as we can hide implementation details of a given service.”

(ref: http://www.amazon.com/Mastering-Web-Application-Development-AngularJS/dp/1782161821).


Usage

Service : Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call(this) or similar.

Factory : Could be useful for returning a ‘class’ function that can then be new`ed to create instances.

So, use a factory when you have complex logic in your service and you don’t want expose this complexity.

In other cases if you want to return an instance of a service just use service.

But you’ll see with time that you’ll use factory in 80% of cases I think.

For more details: http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/


UPDATE :

Excellent post here :
http://iffycan.blogspot.com.ar/2013/05/angular-service-or-factory.html

“If you want your function to be called like a normal function, use
factory. If you want your function to be instantiated with the new
operator, use service. If you don’t know the difference, use factory.”


UPDATE :

AngularJS team does his work and give an explanation:
http://docs.angularjs.org/guide/providers

And from this page :

“Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.”

Leave a Comment