25

I don't know what is the best practice and what I should use.

What is the difference between below two methods?

module.service(..);

and

module.factory(..);
Code Abominator
  • 1,571
  • 18
  • 23
Lion.k
  • 2,519
  • 8
  • 28
  • 43
  • 4
    possible duplicate of [Angular.js: service vs provide vs factory?](http://stackoverflow.com/questions/15666048/angular-js-service-vs-provide-vs-factory) – Mark Rajcok May 15 '13 at 15:20
  • @MarkRajcok it is but the answer here has better examples –  Feb 01 '14 at 16:58

2 Answers2

47

There is a great google group post about this from Pawel Kozlowski:

https://groups.google.com/forum/#!msg/angular/hVrkvaHGOfc/idEaEctreMYJ

Quoted from Powel:

in fact $provide.provider, $provide.factory and $provide.service are more or less the same thing in the sense that all of them are blueprints / instructions for creating object instances (those instances are then ready to be injected into collaborators).

$provide.provider is the most spohisticated method of registering blueprints, it allows you to have a complex creation function and configuration options.

$provide.factory is a simplified version of $provide.provider when you don't need to support configuration options but still want to have a more sophisticated creation logic.

$provide.service is for cases where the whole creation logic boils down to invoking a constructor function.

So, depending on the complexity of your construction logic you would choose one of $provide.provider, $provide.factory and $provide.service but in the end what you are going to get is a new instance.

Here is the accompanying fiddle to demonstrate (from the thread): http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/

And the code:

var myApp = angular.module('myApp', []);

//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!"
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!"
        }
    };
});

//provider style, full blown, configurable version     
myApp.provider('helloWorld', function() {

    this.name = 'Default';

    this.$get = function() {
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!"
            }
        }
    };

    this.setName = function(name) {
        this.name = name;
    };
});

//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});


function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {

    $scope.hellos = [
        helloWorld.sayHello(),
        helloWorldFromFactory.sayHello(),
        helloWorldFromService.sayHello()];
}
lucuma
  • 18,247
  • 4
  • 66
  • 91
  • 2
    +1 There are several more popular questions/answers on the service vs factory (vs provider) concept (and I have gone over them a couple of times), but this is by far the most clear explanation. Would have saved me quite some time, had I found it sooner :) – gkalpak Dec 18 '13 at 13:19
  • what about functions that have dependencies? Can you use the DI notation? `myApp.service('helloWorldFromService', ['$resource', function($resource) {...}`? –  Feb 01 '14 at 16:58
1

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

Code Whisperer
  • 22,959
  • 20
  • 67
  • 85
  • What do you mean by - "But what if each app wants to keep its own tally of things?" I have a single app and everyone too. – Sanjeev Singh Apr 15 '15 at 04:31