HI All,
Today we are discussing about Dependency injection using factory in Angular js.
What is Factory ?
Factory is a function which is used to return value. 
Where we creates value whenever a service or controller requires.
 
In which we used factory function to calculate and return the value.
Here is an example how to use Dependency injection using factory :
<body ng-app="mainApp">
        <div ng-controller="homecontroller">
            <div>
                <form>
                    <p>Enter the radius: <input type="text" name="radius" ng-model="radius"/></p>
                    <input type="button" value="Area" ng-click="submit()"/>
                    <div>The area of circle is {{areaCircle}}</div>
                </form>
            </div>
        </div>
   </body><br>
//define a module
var mainApp = angular.module("mainApp", []);
//define a constant value pi"
mainApp.constant("pi", 3.14);
//create a factory CircleArea" which provides a method multiply to return multiplication of radius and pi.
mainApp.factory('CircleArea', function() {     
   var circlefactory = {};  
   circlefactory.area = function(r) {
      return pi*r*r;
   }
   return circlefactory;
}); 
//inject the factory "CircleArea" in a controller to utilize the circle area method of factory.
mainApp.controller("homecontroller", function ($scope, CircleArea) {
    $scope.submit = function(){
        $scope.areaCircle = CircleArea.Area($scope.radius);
    };
});
                       
                    
0 Comment(s)