Open In App

AngularJS Factory Method

Improve
Improve
Like Article
Like
Save
Share
Report

AngularJS Factory Method makes the development process of AngularJS applications more robust. A factory is a simple function that 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 a 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: A practical Scenario Factory generally acts as a container or class for a collection of functions that fulfills different features of the application. When used with a constructor function it can be initiated within different Controllers. 

Syntax:

module.factory( 'factoryName', function(){ Custom code....});

Example 1: The following example illustrates the use of factory code instantiated inside a controller to generate a random number.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Factory Example 1</title>
    <script src=
    </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 that 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 2: This example makes use of a factory to create a function to find the 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.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Factory Example 2</title>
    <script src=
    </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:



Last Updated : 19 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads