As I understand it, when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using this
I had this confusion for a while and I'm trying my best to provide a simple explanation here. Hope this will help!
angular .factory
and angular .service
both are used to initialize a service and work in the same way.
The only difference is, how you want to initialize your service.
Both are Singletons
var app = angular.module('app', []);
,
)If you would like to initialize your service from a function that you have with a return value, you have to use this factory
method.
e.g.
function myService() {
//return what you want
var service = {
myfunc: function (param) { /* do stuff */ }
}
return service;
}
app.factory('myService', myService);
When injecting this service (e.g. to your controller):
myService()
) to return the object
,
)If you would like to initialize your service from a constructor function (using this
keyword), you have to use this service
method.
e.g.
function myService() {
this.myfunc: function (param) { /* do stuff */ }
}
app.service('myService', myService);
When injecting this service (e.g. to your controller):
new
ing your given function (as new myService()
) to return the objectfactory
with
or service
with
, it will not work.