I'm getting re-acquainted with angular after a long time away, and (so far) I've discovered two ways to create an angular service. The simplest being this:
var app = angular.Module("SomeApp", [])
.factory("SomeService", function ($log) {
$log.info("Yea beh beh! Dis hea is a service!")
});
This form of creating a service in angular is documented in angular.Module.factory. But, you can also see, that on the same page there is another way to create a service, using angular.Module.service.
Reading the two descriptions, I am unable to understand the differences other than .service
needs you to explicitly use new
to instantiate a service, whereas .factory
implicitly does it for you. I might be wrong here, since I'm unable to understand because I have no clue what a $get
property is. So, to wrap up:
- What is a
$get
property? - What is the difference between
.service
and.factory
?
Lastly, because this bugs me:
- With all
angular.Module.{service, factory, controller}
, the second argument is afunction
. But, for instance, you have put in a list for the second argument in acontroller
, and name its dependencies. Then why is the type taken to be afunction
, rather thanobject
? I mean you won't know from the documentation that you can declare dependencies in a list unless you've done a tutorial or something.
-
1possible duplicate of Angular.js: service vs provider vs factory?Klaster_1 Нет войне– Klaster_1 Нет войне2014年09月05日 06:40:47 +00:00Commented Sep 5, 2014 at 6:40
2 Answers 2
Both angular.Module.factory
and angular.Module.service
are proxies to angular.Module.provide
. When you give a function to angular.Module.factory
angular creates the respective service by invoking the function and using its return value as the service. On the other hand, when you give a function to angular.Module.service
angular will treat it as an constructor and invoke it with the new
keyword to create the service.
Thus creating a service with angular.Module.factory
looks like this:
app.factory('MySimpleService', function () {
return {
aServiceProperty : 'a property containing a string'
};
});
And creating a similar service with angular.Module.service
looks like this:
app.service('MyOtherSimpleService', function () {
this.aServiceProperty = 'a property containing a string';
});
3 Comments
.factory
over .service
..factory
to creat a constructor (by returning a function) and .service
to create singleton objects (by writing properties and methods to this
, or returning an instance of a constructor)- The definition of the $get propery can be found here
- Looks like this question has already been asked and answered. I am unable to comment, so I posted an answer.