Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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()];
}
@codeandcats
Copy link

codeandcats commented Jun 11, 2015

Thanks, this is very helpful. :)

@Hemalatah
Copy link

Hemalatah commented Aug 25, 2015

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

vahidalvandi commented Mar 3, 2016

very thanks

@umangparekh001
Copy link

umangparekh001 commented Feb 1, 2017

Many Thanks !

Copy link

ghost commented Mar 29, 2017

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

@shashankGopannagari
Copy link

shashankGopannagari commented Nov 16, 2017

Nice Explanation. Helpful

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