Wednesday 13 May 2015

Injecting dependencies with service.



This section of code is written with an attempt to clear the concept of dependency injection with service. Here a service Calc is created and injected in a controller. I hope you will like this section of code and do comment if you have any queries regarding any part of it. I have notadded any separate app.js file but added all the code within a file with script tag.

<html ng-app="app">
<head>
<title>
    Injecting dependency in services.
</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',[]);
    //Creating service with two functions which will be injected later on into the controller.
    app.service('CalcService',function() {
        this.Add = function(a,b) {
            return parseFloat(a) + parseFloat(b);
        };
        this.Multiply = function(a,b) {
            return a * b;
        };
    });
   // You can find how CalcService is injected into the controller
    app.controller('MainCtrl',function($scope,CalcService) {
        $scope.AddNumbers = function() {
        $scope.resultNum = CalcService.Add($scope.firstNum,$scope.secondNum);
        };
        $scope.MultiplyNumbers = function() {
        $scope.resultNum = CalcService.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="Multiply Number" ng-click="MultiplyNumbers()" / ><br />
<span>Result Value : {{resultNum}}</span>
</body>
</html>

No comments: