
AngularJS: Factory vs. Service vs. Provider - tm33
http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/
======
chao-
I enjoy quite a few parts of Angular, but its choice of naming between
Factories & Services is maddening. The fact that Factories are not Factories-
as-seen-in-any-other-context made me sad. Unless I am mistaken, from what I
have seen:

Angular Factories are Singletons (you always get the same object).

Angular Services are Factories (you can get many independent instances of an
object from them).

~~~
minznerjosh
Really, Services and Factories are just a shorthand way of creating providers.

.factory('foo', function() {

    
    
      var foo = {};
    
    
      return foo;
    

});

is the same as:

.provider('foo', function() {

    
    
      this.$get = function() {
    
        var foo = {};
    
    
        return foo;
    
      };
    

});

And,

.service('foo', function() {

    
    
      this.bar = 'bar';
    

});

is the same as:

.factory('foo', function() {

    
    
      function Foo() {
    
        this.bar = 'bar';
    
      }
    
    
      return new Foo();
    

});

is the same as:

.provider('foo', function() {

    
    
      this.$get = function() {
    
        function Foo() {
    
          this.bar = 'bar';
    
        }
    
    
        return new Foo();
    
      }
    

});

~~~
acoyfellow
So when should we use each?

~~~
minznerjosh
That can be a matter of personal preference, so the best I can do is share my
preference.

I usually use the "service" method because most of my services are objects,
and I have no aversion to constructor functions.

However, if I want my service to be a function (a la $http or $timeout,) I'll
use a factory (because I don't want a constructor to be new-ed, I just want to
create a function.)

And, as the article states, I'd use a provider if I want to provide methods to
configure my service before it is instantiated.

I think a lot of it comes down to semantics. Maybe it's just me, but
describing my object via a constructor function (as a "service") makes it feel
a bit weightier than creating and returning a POJO in a factory. But, from a
practical standpoint, you can see it as this:

A provider is responsible for creating (providing) an injectable (as a
singleton) object that others can request to be injected. The provider creates
this object in its $get method. It can also have methods/properties other than
$get that can be called/modified in the config stage to configure the object
it will create.

But, often times (maybe the majority of times,) you don't need to configure
your injectable before it is created, so we really only care about the $get
method of the provider. This is where the "factory" API comes in. It just
eliminates all the boilerplate around creating a provider that only has a $get
method.

And finally, for reasons that are not entirely clear to me, the angular team
also decided to provide a shorthand for creating a constructor, and returning
a new instance of that constructor in the $get method of the provider (or the
factory function if you like.) And that's what the "service" API is.

So, the provider is the root API, factory is sugar on top of the provider API,
and service is sugar on top of factory API.

------
Geee
Yesterday, I spent 8 hours writing an AngularJS directive for setting focus on
an input field. You know, last year we used to just
document.getElementById('myfield').focus(), but it's much more reusable and
maintainable with a custom 'focusable' directive.

If you want to learn more about the subject:
[http://stackoverflow.com/questions/14833326/how-to-set-
focus...](http://stackoverflow.com/questions/14833326/how-to-set-focus-in-
angularjs)

~~~
zoomerang
If you can solve something in jQuery, why are you using Angular? Wrong tool
for the job.

If you have an application that otherwise uses Angular, and you have a snippet
of jQuery code that you want to use, wrapping it in a directive takes about 30
seconds. Alternatively, if you don't want to write a directive, you can just
run the jQuery code directly as if Angular didn't even exist.

~~~
chazu
To me, a large part of the value proposition behind angular is in a) making
your app as declarative as possible and b) isolating resuable and imperative
code in modules (directives or services in the parlance of angular).

------
cabbeer
I don't know if Angular is stupid or I am.

~~~
thenerdfiles
It's when Angular has to play with something else, some other library or
plugin. And the more Angular Modules you outsource, the hope is that you're
all using Directives and Promises rigorously. It gives templates a lot more
say in terms of complexity.

Some days my vim looks like (mostly Directives):

    
    
        ----------------------------
        |    |    |    |     |     |
        |    |    |    |-----------|
        |    |    |    |     |     |
        |    |    |    |-----------|
        |    |    |    |     |     |
        ----------------------------
        

And I'm thinking: Oh god what's happening, is this the abyss?

~~~
joevandyk
You can put more than one directive in a file. If it gets too unweildy,
separate stuff into separate files based on functionality (ordering.js,
login.js, shared_ui.js, etc)

------
IgorPartola
Angular reminds me of Puppet in an odd way. Reading the Puppet docs you will
come across passages that say "in the recent release we have added this new
feature. Do not use it as it is not well thought through and here is the old
simple reliable way to get what you want done." Angular seems to suffer from
the same problem. Services are completely unnecessary as Factories are a far
simpler and superior way of doing things. Providers are a terrible way to do
things. Instead a config service (with a lowercase s) should handle getting
initial values to the Factory. The DI system that works in dev but not prod
unless you use the explicit way of listing your dependencies is another
example of this.

------
olalonde
What I like about Angular: the scope system, two way binding, clever use of
HTML markup for templating. I just wish it was more library like and less like
a framework. I guess what I would really like to see is a hybrid of Backbone
and Angular. Does such a thing exist?

~~~
hcarvalhoalves
After successfully implementing a project with React.js + Backbone models and
routers, I'm now sure Angular is both unnecessarily complex _and_ limited.

One of the nicest things about React.js is not having to deal with such a
layered architecture, you work at the right level of abstraction
("components"), and those components are composable. Some people freak out
with JSX but it pays off to finally have a proper GUI pipeline for web apps
instead of manipulating the DOM directly, or being limited to directives
embedded in HTML.

~~~
nahname
Do you have any open source projects for others to learn from?

Used backbone a few times, always turns into a train wreck.

~~~
hcarvalhoalves
Unfortunately it's a commercial product so no source. Drop me a mail though
(see profile), I can give some pointers.

I know what you mean by Backbone, and all I can say is that often wiring up
the views is the culprit. Models and routers work nicely and that's all I used
from Backbone in this project.

------
camus2
the guy didnt want to name them singelton (because it is what hey are
basically), because of bad rep,so he went with factory/service/provider. It's
like naming your presenter controllers when they are not controllers. Angular
definetly has a nomenclature problem which make it difficult to understand at
first, but its concepts are quite simple and elegant.

------
bryan_rasmussen
Finally I feel like I understand Java.

Was that too snarky?

~~~
carsongross
Exactly. How did we end up porting J2EE to the _client side_? People appear to
think this is a good idea because... javascript? Because google?

It's crazy.

[http://intercoolerjs.org/why.html](http://intercoolerjs.org/why.html)

~~~
alttab
I was reading through this and thinking "holy crap these angularJS guys are
missing the entire point." They are running a damn app-server inside the
browser page, for the love of god!

~~~
fineline
Well, I'm missing it - what exactly is "the point"? When building client side
applications that have hundreds of components and must be able to function in
a stand-alone mode robustly, potentially over multiple user sessions, until a
network connection becomes available, having access to a robust implementation
of proven, testable software development patterns makes sense to me. It did
when I was building those client-side apps in Java or .NET, what changes now I
am building them in the language with wider reach than any other in history?
All of a sudden I should approach it like a script kiddy?

~~~
alttab
Building a client side application that has hundreds of components and be able
to function in a stand-alone mode robustly, potentially over multiple user
sessions, until a network connection becomes available, having access to a
robust implementation of proven, testable software development patterns:

\- Objective C \- Java + Android \- Monad and #C

Why are we killing ourselves with browsers? I mean, to a degree I get the
cross platform deal... but unless you are building for exactly that
environment (ie NOT A WEB APPLICATION) then it doesn't make sense to me... at
all. There are better tools.

