What is the Difference Between factory and service in AngularJS ?
Last Updated :
02 Aug, 2023
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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</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:
.gif)
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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</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:
.gif)
Difference between Factory and Service
|
It returns an object in AngularJS. | It returns a constructor function. |
Shared instance across the application | Shared instance across the application |
It is preferred for complex objects and dependencies | It is used for simple objects and functionality. |
It can be configured before returning the object | The configuration is done within the constructor. |
Detailed error messages during creation. | Less informative error messages during creation. |
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read