Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Dependency injection using Factory in Angularjs

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 352
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: