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