2

This maybe a stupid question, maybe it's just about wordings. I am learning about AngularJS and reading lots of article, I saw a strange happens. Lots of people say "use a services", but in the code they use "factory" instead.

for example, these question : Pass variables to AngularJS controller, best practice?, Angularjs sharing methods between controllers

Why the people say 'A' and using 'B', can't you just say "you can use factory" ? I ask this question because i saw it more than a few time, which confuse me ...services and factory is two different thing, right ?

Community
  • 1
  • 1
user3662467
  • 163
  • 1
  • 2
  • 7

3 Answers3

1

There really is no difference between the two other than one is new'ed up while the other is not. Other than that, they are both singletons and injectable. You also use them in pretty much the same way.

I too was confused like you, but because of the similarity, I now tend to use the term interchangeably.

Michael Kang
  • 52,003
  • 16
  • 103
  • 135
0

I think the reason for the interchangeability of the words comes down to the similarity between them. There is little chance in the context of most conversations that what you say about one does not apply to the other. Just keep that in the back of your mind, and more importantly learn the difference, and it will seem a bit less confusing.

See the below question for a great explanation on the difference (other good references in the comments as well).

confused about service vs factory

Community
  • 1
  • 1
aw04
  • 10,857
  • 10
  • 56
  • 89
0

A factory is what actually creates your service; it ends up being a service anyway. In AngularJS, you have three ways to declare a service; using value, which pretty much creates a static service instance, using factory, which lets you configure it before it is created, and using provider which even lets you override dependencies.

See the related question in my comment to your question, and you'll also find details on AngularJS's documentation (https://docs.angularjs.org/guide/services) and even more if you look into their source code.

To make it very simple, it's the same reason you won't use the same word for "constructor" and "instance", just in another context.

Christian Rondeau
  • 4,143
  • 5
  • 28
  • 46
  • So can I say a "factory" is a constructor function, and we call the instance of it as "service" ? – user3662467 Jun 18 '14 at 01:53
  • Not exactly, but you got the idea. Since a service is always a singleton, it's not the same; to make things a little bit more complicated, your service *could * be a constructor (it's JavaScript! Your service can be an object, a string, a function...) - in the end, the service object itself, whatever it is, will be created by a factory. – Christian Rondeau Jun 18 '14 at 11:55