Skip to content

Instantly share code, notes, and snippets.

@Mithrandir0x
Created September 5, 2012 16:15
Show Gist options
  • Save Mithrandir0x/3639232 to your computer and use it in GitHub Desktop.
Save Mithrandir0x/3639232 to your computer and use it in GitHub Desktop.
Difference between Service, Factory and Provider in AngularJS
// Source: https://groups.google.com/forum/#!topic/angular/hVrkvaHGOfc
// jsFiddle: http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/
// author: Pawel Kozlowski
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() {
// In the provider function, you cannot inject any
// service or factory. This can only be done at the
// "$get" method.
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()];
}​
@contextworks
Copy link

Simply great examples. Very useful, thanks a lot.

@WiechersV
Copy link

Thank you very much, this is very enlightening!

I also recommend people to take a look at angular.js source code to understand it better, most specifically, search for the createInjector function, that's the one who hold all the logic of Angular DI, services, factory, services, etc.!

@doup
Copy link

doup commented Sep 3, 2013

You can't inject a service in app.config(), so if you want to pass a service to the provider just inject it in $get:

app.provider('settings', function () {
    this._settings = {};

    this.$get = ['cache', function (cache) {
        var settings = new Settings(cache);

        settings.setSettings(this._settings);

        return settings;
    }];

    this.setSettings = function (settings) {
        this._settings = settings;
    };
});

@waskito
Copy link

waskito commented Nov 8, 2013

@doup you say that we can inject service in $get. Can I inject $cookieStore in $get ?

@uncletomiwa
Copy link

Finally, I understand it

@mrn-aglic
Copy link

Thank you for the great examples!

@AlexCppns
Copy link

What I see is different ways of doing the same thing so far. Can I get an example where one MUST use a service for instance? When using a factory doesnt cut it and you have to use a provider?

@andrezero
Copy link

Most of the examples above give you a use case for a provider:

look in the first example how you can call setName() on the provider to configure the service. It's under "//hey, we can configure a provider!"

@LeftOverCoder
Copy link

Service is singleton and simple version of Factory. While Factory is a simple version of Provider, Factory is a more flexable compared to service method, and a short handed for configuring a service when $get method is required. Provider creates new object by the $get factory function. Provider is not injectable during run phase or run time while all others are ( Constant, Variable, Service, and Factory), however, Provider is injectable during the configuration phase or compile time.

Provider should be used very sparely as you want to use compile time injection. Usually, Service does most of the job while Factory can deal with more sophisticated logic. Remember, Service is a singleton so if you need to create new object every time, use Factory instead.

@dmitriz
Copy link

dmitriz commented Apr 22, 2014

Here is a very simple example of provider without 'this':
http://jsbin.com/xolom/2/edit

@sunew
Copy link

sunew commented May 26, 2014

@gigablox : Thanks for the super example, that really got it working for me. A question/comment: Instead of using events to signal data is ready, wouldn't it be a good just to return a promise. And then let the controller set then on the promise, and set data on the scope from then?

@topstardev0000
Copy link

thanks for useful code block. but I would be happy if you explain each type, purpose and when to use which one.

@joshids
Copy link

joshids commented Jun 24, 2014

  1. When you register the Service you return an object, when Angular needs to inject "service" into any component, it will inject this object.
  2. When you register the Factory, you return a constructor function. When angular needs to inject "service" into any component, it will first do a

new factoryReturnedFunction();

and then inject it. This will be done only for the first time service is requested. For all subsequent injections, object created first time will be used.
3. When you register a Provider, it has same behavior as Factory above. The function assigned to ...$get..., will be used as constructor function.

@expalmer
Copy link

expalmer commented Jul 9, 2014

thanks for sharing, you help me alot to understand.

Copy link

ghost commented Jul 21, 2014

Nice Info

@Webenius
Copy link

@Mithrandir0x, thank you for the example!
If we need a service and we define it using the "factory" method, is it write or false?

https://github.com/SAM-BI/jira-rest-angular

@codeandcats
Copy link

Thanks, this is very helpful. :)

@Hemalatah
Copy link

Thanks much for the explanation. would you tell me, where to use which, I mean, how to make a right choice among them?
Appreciate your time

@xis19
Copy link

xis19 commented Nov 18, 2015

Thanks for the helpful example.

@vahidalvandi
Copy link

very thanks

@umangparekh001
Copy link

Many Thanks !

Copy link

ghost commented Mar 29, 2017

Nice explanation about Service / Provider / Factory, Very useful, Thank you very much !

@shashankGopannagari
Copy link

Nice Explanation. Helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment