AngularJS service vs factory – with example

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.

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

http://blog.manishchhabra.com/2013/09/angularjs-service-vs-factory-with-example/

Advertisements

4 thoughts on “AngularJS service vs factory – with example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s