AngularJS - difference between Service, Factory and Provider

Services

Syntax: module.service( 'serviceName', function ); Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().

Factories

Syntax: module.factory( 'factoryName', function ); Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Providers

Syntax: module.provider( 'providerName', function ); Result: When declaring providerName as an injectable argument you will be provided with ProviderFunction().$get(). The constructor function is instantiated before the $get method is called - ProviderFunction is the function reference passed to module.provider.

Providers have the advantage that they can be configured during the module configuration phase.

js:

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

html:

<div ng-controller="MyCtrl">{{hellos}}</div>

Leave a Reply

Your email address will not be published. Required fields are marked *