AngularJS | Factory Method - GeeksforGeeks

30 Aug, 2019
AngularJS Factory Method makes the development process of AngularJS application more robust. A factory is a simple function which allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application. Whenever we create an object using factory it always returns a new instance for that object. The object returned by the factory can be integrated(injectible) with different components of the Angularjs framework such as controller, service, filter or directive.
Use:In practical Scenario Factory generally acts as container or class for a collection of functions which fulfills different features of the application. When using with a constructor function it can be initiated within different Controllers.
Syntax:
module.factory( 'factoryName', function(){ Custom code....});
Example:The Following example illustrate the use of factory code instantiated inside a controller to generate a random number
<!DOCTYPE html><html>  <head>    <title>Factory Example 1</title>      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script>    <script>        var application = angular.module('myApp', []);          application.factory('random', function() {            var randomObject = {};            var number = Math.floor(Math.random() * 100);            randomObject.generate = function() {                return number;            };            return randomObject;        });                application.controller('thisapp', function($scope, random) {            $scope.generateRandom = function() {                $scope.randomNumber = random.generate();            };        });    </script></head>  <body>    <h1 style="color:green">GeeksforGeeks</h1>    <h2>Factory Examples</h2>    <div ng-app="myApp" ng-controller="thisapp">        <button ng-click="generateRandom()">          Generate Random Number      </button>        <br>{{randomNumber}}    </div></body>  </html>
Output:
On Clicking the generate random number button we get a different number every time. In this example, we use the factory method to define a function which carries a variable and using the Math.random we store a random value to that variable every time this function is called. This function is then called in the controller whose $scope variable carries the random value from the called function we then call this controller to our HTML code to display the result.
Example: This example make use of factory to create a function to find addition or subtraction of two numbers. this function is then loaded in the controller $scope variable which passes them to the html code for displaying the results.
<!DOCTYPE html><html>  <head>    <title>Factory Example 2</title>    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script>    <script>        var application = angular.module('myApp', []);          application.factory('MyFactoryService', function() {            var factory = {};            factory.Subtract = function(a, b) {                return a - b;            };            factory.Add = function(a, b) {                return a + b;            };            return factory;        });          application.controller('thisapp', function(                               $scope, MyFactoryService) {            $scope.result = function() {                $scope.results =                   MyFactoryService.Subtract($scope.num1, $scope.num2)            };            $scope.result2 = function() {                $scope.results =                   MyFactoryService.Add($scope.num1, $scope.num2)            };        });    </script></head>  <body>    <h1 style="color:green">GeeksforGeeks</h1>    <h2>Factory Example 2</h2>    <div ng-app="myApp" ng-controller="thisapp">        <p>            Enter A Number:            <input type="number" ng-model="num1" />            <br/> Enter A Number:            <input type="number" ng-model="num2" />            <br/>        </p>        <button ng-click="result()">Subtract</button>        <button ng-click="result2()">Add</button>        <p>Results: {{results}}    </div></body>  </html>
Output:Before:
After entering the input clicking on the add/subtract button displays the result:
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?