Monday, March 10, 2014

AngularJS service vs factory – with example

AngularJS service vs factory – with example

Also read my answer on stackoverflow (angular.service vs angular.factory).

What is an AngularJS service or factory?

Singleton.
Yes! That one word is enough to define AngularJS services. The purpose of AngularJS service / factory function is to generate a single object or function that represents the service to rest of the application. That object or function is passed as a parameter to any other factory function which specifies a dependency on this service.

Services

Syntaxmodule.service('serviceName', function);
Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.
Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call(this) or similar.
Example:
var app = angular.module('myApp', []);
    
// Service definition
app.service('testService', function(){
    this.sayHello= function(text){
        return "Service says \"Hello " + text + "\"";
    };        
});

// AngularJS Controller that uses the service
function HelloCtrl($scope, testService)
{
    $scope.fromService = testService.sayHello("World");
}

Factories

Syntaxmodule.factory('factoryName', function);
Result: When declaring factoryName as an injectable argument you will be provided the value that is returned by invoking the function reference passed to module.factory.
Usage: Could be useful for returning a ‘class’ function that can then be new’ed to create instances.
var app = angular.module('myApp', []);

// Factory
app.factory('testFactory', function(){
    return {
        sayHello: function(text){
            return "Factory says \"Hello " + text + "\"";
        }  
    }               
});

// AngularJS Controller that uses the factory
function HelloCtrl($scope, testFactory)
{
    $scope.fromFactory = testFactory.sayHello("World");
}

Here is a running code on jsfiddle which you can test and play with.

No comments:

Post a Comment