Wednesday, 13 May 2015

Factory versus service in Angular JS



In my previous post I have shown how to inject service dependencies in Angular JS. This portion of code shows difference between service and factory. I have created one service and one factory  Although I have used only the factory but you can replace the factory with the service injecting inside the controller.

<html ng-app="app">
<head>
<title>
    Difference between factory and service.
</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript">
    app = angular.module('app',[]);
    app.factory('CalcFactory',function() {
        return {
        Add: function(a,b) {
            return parseFloat(a) + parseFloat(b);
        },
        Multiply: function(a,b) {
            return a * b;
        }
        }
    });

    app.service('CalcService',function() {
        this.Add = function(a,b) {
            return parseFloat(a) + parseFloat(b);
        };
        this.Multiply = function(a,b) {
            return a * b;
        };
    });  

    app.controller('MainCtrl',function($scope,CalcFactory,CalcService) {
        $scope.AddNumbers = function() {
        $scope.resultNum = CalcFactory.Add($scope.firstNum,$scope.secondNum);
        };
        $scope.MultiplyNumbers = function() {
        $scope.resultNum = CalcFactory.Multiply($scope.firstNum,$scope.secondNum);
        };
    });

</script>
</head>
<body ng-controller="MainCtrl">
<label>Enter First Number : </label>
<input type="text" name="firstNum" ng-model="firstNum" value="" /><br />
<label>Enter Second Number : </label>
<input type="text" name="secondNum" ng-model="secondNum" value="" /><br />
<input type="button" value="Add Number" ng-click="AddNumbers()" / ><br />
<span>Result Value : {{resultNum}}</span>
</body>
</html>
 

No comments: