AngularJS - Difference between Service, Factory and Provider in AngularJS

https://gist.github.com/Mithrandir0x/3639232

by gavinfoley

HTML

<script src="http://code.angularjs.org/angular-1.0.0.js"></script>
<div ng-controller="MyCtrl">
    {{hellos}}
</div>

CSS

/*
Here is the response I've posted a while ago to a very similar 
question about service, factories and providers (jsFiddle included!): 

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 jsFiddle showing different ways of constructing objects: 
http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/ 


The angular documentation is quite OK regarding this topic: 
http://docs.angularjs.org/api/AUTO.$provide 

Cheers, 
Pawel 
*/

JavaScript

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

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

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "factory - 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 "provider - 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()];
}