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 is pipe() function in Angular ?
Angular stands out as a liked JavaScript framework for developing web applications. In Angular, the pipe() function plays a vital role in transforming data within templates. It allows you to apply various transformations to data before displaying it in the view. In this article, we will explore more
4 min read
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 are the Types of Linking Function in Angular ?
When working with Angular directives, understanding the concept and types of linking functions is essential. Linking functions are a crucial part of the directive's lifecycle, allowing developers to interact with the directive's DOM element and scope. In this article, we will explore the different t
4 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 is a custom directive in Angular?
Angular, a popular framework for building dynamic web applications, offers a powerful feature known as custom directives. These directives extend the functionality of HTML elements, enabling to create reusable components and add behavior to their applications. In this article, we'll learn about the
4 min read
What is entryComponents in angular ngModule ?
The entryComponent is the component which loads angular by force, that means these components are not referenced in the HTML template. In most of the cases, Angular loads a component when it is explicitly declared in the component template. But this is not the case with entryComponents. The entryCom
3 min read
What are angular Material Icons ?
Angular Material is a UI component library which is developed by Google so that Angular developers can develop modern applications in a structured and responsive way. By making use of this library, we can greatly increase the user experience of an end-user thereby gaining popularity for our applicat
3 min read
AngularJS angular.isObject() Function
The angular.isobject() Function in AngularJS is used to determine if the parameter inside isobject function is an object or not. It returns true if the reference is an object or else false. Syntax: angular.isobject(value);Parameter: value: This parameter value validates whether the entered value is
2 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