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()];
}​
@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