AngularJS Factory



  • Factory method is one of the services in AngularJS.
  • AngularJS factory method is generating a singleton object or injectable function. The object or function is passed as a parameter to any other factory function which specifies a dependency on this service.

Syntax for Factory service in AngularJS:

app.factory(‘factoryname’, function()
{  …………  
});

Sample Coding for Factory service in AngularJS:

 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorial</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
        angular.min.js"> </script>
    </head>
    <body>
        <div ng-app="myApp" ng-controller="factoryCtrl">
            <h3>square value using factory method in AngularJS</h3>
            <p>square value of 50 is<b>{{ result}}</b></p>
        </div>
        <script>
            var app = angular.module('myApp', []);
            app.factory('square', function() {         
                 var factory= { }; 
                factory.myFunc = function (a) { 
                   return a*a;   
                }   
                return factory;  
            });  
             app.controller('factoryCtrl', function($scope, square) {
               $scope.result = square.myFunc(50);  
            }); 
        </script>
    </body>
</html>

Code Explanation for Factory service in AngularJS:

Code Explanation for AngularJS Factory

  1. The ng-app specifies the root element (“myApp”) to define AngularJS application.
  2. The ng-controller control the data of “factoryCtrl” in AngularJS application.
  3. Here create factory services (app.factory) and the factory name is given as “square”.
  4. variable is used to declare the method of factory (factory={ }) and factory method is used to create a Function(myFunc) is return the square value of “a” and the value gets from the scope object($scope.result).
  5. The “square” factory service is added with the controller function.
  6. $scope.result is used to declare the square value is 50 and the output will be updated in the <script> tag.

Sample Output for Factory service in AngularJS:

Sample Output for AngularJS Factory

  1. The output displays the square value is 2500.


Related Searches to angularjs Factory