I don\'t know what is the best practice and what I should use.
What is the difference between below two methods?
module.service(..);
<
Consider the following service.
angular.module("myModule", [])
.service("thingCountingService", function() {
var thingCount = 0;
this.countThing = function() { thingCount++; }
this.getNumThings = function() { return thingCount; }
});
If you had an app, in which a variety of controllers, views, etc, all want to contribute to one general count of things, the above service works.
But what if each app wants to keep its own tally of things?
In that case, a singleton service would not work since it can only keep track of all of them. However, a factory lets you create a new service every time you want to start a new counter.
angular.module("myModule", [])
.factory("thingCountingServiceFactory", function() {
var thingCount = 0;
this.countThing = function() { thingCount++; }
this.getNumThings = function() { return thingCount; }
});
With the above factory, you can call new thingCountingServiceFactory()
at any time and get a new thingCountingService
set to 0