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>
        <title>Wikitechy AngularJS Tutorial</title>
        <script src="
        angular.min.js"> </script>
        <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>
            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);  

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