Open In App

What is the Difference Between factory and service in AngularJS ?

Last Updated : 02 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a <script> tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions.

In this article, we will explore the differences between the factory and service in AngularJS and provide examples to illustrate their usage. Two commonly used methods for creating services in AngularJS are factories and services. While they serve a similar purpose, there are some key differences between the two.

AngularJS factory

A factory in AngularJS is a function that returns an object. It allows us to define and configure the object before returning it. Factories are used to create singleton objects, which means that AngularJS will create the object once and then reuse it whenever the factory is injected into different components of the application. This enables the sharing of data and functionality across the application.

Syntax:

app.factory('userService', function () {
var user = {
name: 'Geek',
age: 30
};

return {
getUser: function () {
return user;
},

setUser: function (newUser) {
user = newUser;
}
};
});

Example: Below example demonstrates the usage of the factory in AngularJS. Here, In the example, when the user clicks the button, it changes the name to a different name using a factory.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>
          AngularJS Factory vs Service Example
      </title>
    <script src=
      </script>
</head>
  
<body ng-controller="UserController" 
      style="text-align: center;">
    <h1 style="color: green;">
          GeeksforGeeks
      </h1>
    <h2>Factory usage</h2>
    <p>Name: {{factoryUser.name}}</p>
    <button ng-click="changeFactoryUser()">
          hange Name
      </button>
  
    <script>
        
        // Define the AngularJS module
        var app = angular.module("myApp", []);
  
        // Define the factory
        app.factory("userServiceFactory", function () {
            var name = {
                name: "Welcome to",
            };
  
            return {
                getUser: function () {
                    return name;
                },
  
                setUser: function (newName) {
                    name = newName;
                },
            };
        });
  
        // Define the controller
        app.controller("UserController", [
            "$scope",
            "userServiceFactory",
            function ($scope, userServiceFactory) {
                
                // Access the factory user
                $scope.factoryUser = userServiceFactory.getUser();
  
                // Change the factory user
                $scope.changeFactoryUser = function () {
                    userServiceFactory.setUser({ name: 
                              "Welcome to GeeksforGeeks!" });
                    $scope.factoryUser = userServiceFactory.getUser();
                };
            },
        ]);
    </script>
</body>
  
</html>


Output:

ezgifcom-crop-(36)

AngularJS Service

A Service in AngularJS is a constructor function. When a service is injected into different components, AngularJS creates a new instance of the service using the ‘new’ keyword. Services are also singleton objects, meaning the same instance is shared across the application.

Syntax:

app.service('userService', function () {
this.user = {
name: 'Geek',
age: 30
};

this.getUser = function () {
return this.user;
};

this.setUser = function (newUser) {
this.user = newUser;
};
});

Example: Below example demonstrates the usage of service in AngularJS. Here, in the example, when the user clicks the button, it changes the name to a different name using a service in AngularJS.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <title>
          AngularJS Factory vs Service Example
      </title>
    <script src=
      </script>
</head>
  
<body ng-controller="UserController" 
      style="text-align: center">
    <h1 style="color: green">
          GeeksforGeeks
      </h1>
    <h2>Service usage</h2>
    <p>Name: {{serviceUser.name}}</p>
    <button ng-click="changeServiceUser()">
          Change Name
      </button>
  
    <script>
        var app = angular.module("myApp", []);
  
        // Define the service
        app.service("userServiceService", function () {
            this.user = {
                name: "Hello",
                age: 30,
            };
  
            this.getUser = function () {
                return this.user;
            };
  
            this.setUser = function (newUser) {
                this.user = newUser;
            };
        });
        
        // Define the controller
        app.controller("UserController", [
            "$scope",
            "userServiceService",
            function ($scope, userServiceService) {
                
                // Access the service user
                $scope.serviceUser = userServiceService.getUser();
  
                // Change the service user
                $scope.changeServiceUser = function () {
                    userServiceService.setUser({ name: "Hello Geek!" });
                    $scope.serviceUser = userServiceService.getUser();
                };
            },
        ]);
    </script>
</body>
  
</html>


Output:

ezgifcom-crop-(37)

Difference between Factory and Service

Basis

Factory

Service

Define It returns an object in AngularJS. It returns a constructor function.
Singleton Shared instance across the application Shared instance across the application
Usage It is preferred for complex objects and dependencies It is used for simple objects and functionality.
Configuration It can be configured before returning the object The configuration is done within the constructor.
Error handling Detailed error messages during creation. Less informative error messages during creation.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads