Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • AngularJS Tutorial
  • AngularJS Directives
  • AngularJS Functions
  • AngularJS Filters
  • AngularJS Examples
  • AngularJS Interview Questions
  • Angular ngx Bootstrap
  • AngularJS Cheat Sheet
  • AngularJS PrimeNG
  • JavaScript
  • Web Technology
Open In App
Next Article:
What is the AppModule in Angular ?
Next article icon

What is the factory function in Angular ?

Last Updated : 16 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

 

Next Article
What is the AppModule in Angular ?

A

apurvabpatil712
Improve
Article Tags :
  • Technical Scripter
  • Web Technologies
  • AngularJS
  • Technical Scripter 2022

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences