What is the factory function in Angular ?
Last Updated :
16 Feb, 2023
In Angular, the factory function is always inclined towards class and constructors. Generally, the factory function is used to provide service as a dependency in any angular application. A factory function generates an object, provides it with some logic, executes the function, and returns the object. It is also used to create directives, also used to invoke a method. Most of the time it is used in arithmetic and mathematical operations. Using a factory function provides ease in reusing and maintaining the code of an application. Factory functions are, by default, used to create single-page applications. Since they are used to create single-page applications, therefore their object can be used in multiple instances. They have the freedom to create an object of any type on their own requirement. They are used to create private and protected codes. An interesting fact is a service and factory function generate the same output, but the difference is when which Angular Service should be used.
Syntax:
var module = angular.module('myapp', []);
module.factory('serviceName', function(){
return serviceObject;
});
A module is created and a factory function is assigned with a service and some function is linked with it and then the object used in the service is returned after the process. There are many reasons for which the factory function should be used, among which a few of them are described below:
- If a value is to be returned, then the factory function should be used.
- By default, Angular uses it in case of service.
- While building an application, if the application is complex then use the factory function.
- If a function is to be used along with mathematical operations or some other function then the factory function should be used.
- When any object is required to be initiated, then the factory function should be used.
- It provides ease while creating private components.
- It primarily provides more flexibility with Javascript functions.
Example 1: In this example, a factory function is created named "myFactory", in which logic is combined to print a message on the screen. After the logic is executed then the msg i.e. the object that is created is returned after the process is completed.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Angular Factory Service Example
</title>
<script src=
"http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<script type="text/javascript">
var app = angular.module('myApp', []);
// Creating Factory
app.factory('myFactory', function () {
var displayFact;
var addMSG = function (msg) {
displayFact = ' Hi Geeks! Welcome to ' + msg;
}
return {
setMSG: function (msg) {
addMSG(msg);
},
getMSG: function () {
return displayFact;
}
};
});
app.controller("myCtrl", function ($scope, myFactory) {
//Inject factory to controller.
myFactory.setMSG(
"GeeksforGeeks Learning. This is an example of Angular factory function");
$scope.myCollections = [
myFactory.getMSG(),
];
});
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="coll in myCollections">
{{coll}}
</div>
</div>
</body>
</html>
Output:
Example 2: In this example, the factory function is assigned with the arithmetic operation, which is named "calculatorService".After all the processes are executed, then the object is returned in the form of output.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Angular Factory function</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js">
</script>
<script>
//Defining Factory
var app = angular.module('app', []);
app.factory('calculatorService', function () {
var calculator = {};
calculator.multiply = function (a, b) { return a * b };
calculator.add = function (a, b) { return a + b };
calculator.subtract = function (a, b) { return a - b };
calculator.divide = function (a, b) { return a / b };
return calculator;
});
app.controller('CalculatorController',
function ($scope, calculatorService) {
$scope.doMultiply = function () {
$scope.answer =
calculatorService.multiply($scope.number, $scope.number);
}
$scope.doAddition = function () {
$scope.answer =
calculatorService.add($scope.number, $scope.number);
}
$scope.doSubtraction = function () {
$scope.answer =
calculatorService.subtract($scope.number, $scope.number);
}
$scope.doDivision = function () {
$scope.answer =
calculatorService.divide($scope.number, $scope.number);
}
});
</script>
</head>
<body style="background-color: #618235;">
<h1 style="color: rgb(214, 205, 205);">
GeeksforGeeks
</h1>
<h3 style="color: rgb(214, 208, 208);">
Angular Factory function
</h3>
<fieldset style="background-color : #FFFACD;">
<legend>AngularJS Factory Function</legend>
<div ng-app="app">
<div ng-controller="CalculatorController">
Enter a number:
<input ng-model="number"
type="number">
<button ng-click="doMultiply()">
Multiply
</button><br>
Enter a number:
<input ng-model="number"
type="number">
<button ng-click="doAddition()">
Addition
</button> <br>
Enter a number:
<input ng-model="number"
type="number">
<button ng-click="doSubtraction()">
Subtraction
</button> <br>
Enter a number:
<input ng-model="number"
type="number">
<button ng-click="doDivision()">
Division
</button>
<p style="font-family:Arial;
color:yellow;
background:steelblue;
padding:3px;
width:350px;">
Answer: {{answer}}
</p>
</div>
</div>
</fieldset>
</body>
</html>
Output:
Similar Reads
What are factory functions in JavaScript ? In JavaScript, a factory function is a function that returns an object. It is a way of creating and returning objects in a more controlled and customizable manner. Factory functions are a form of design pattern that enables the creation of objects with specific properties and behaviors. Why it is us
2 min read
What is the AppModule in Angular ? In Angular, AppModule plays an important role as the entry point to an Angular application. In this article, we'll learn about what AppModule is, its structure, and its significance in Angular applications. We'll also look at some examples to have a clear understanding. Table of Content What is AppM
4 min read
What are decorators in Angular? In Angular decorators are important for defining and configuring various application elements, providing an easy way to enhance the classes with additional functionality and provide metadata. In this article, we'll take a detailed look at the concept of Decorators in Angular. Table of Content What a
4 min read
What is CommonModule in Angular 10 ? In this article, we are going to see what is CommonModule in Angular 10 and how to use it. CommonModule is used to export all the basic Angular directives and pipes. It is re-exported when we import BrowserModule into our angular application, BrowserModule is automatically imported into our applicat
2 min read
What is Angular Expression ? Angular is a great, reusable UI (User Interface) library for developers that help in building attractive, and steady web pages and web application. In this article, we will learn about Angular expression. Table of Content Angular ExpressionDifferent Use Cases of Angular ExpressionsSyntaxApproach Ang
4 min read