Wednesday, 15 April 2015

Creating service and injecting dependencies with AngularJS

Hello everyone. As I am new to AngularJS and I am finding this framework app tremendously exciting making your web programming so simple and simple for users also. Today I came up with using service as dependency injection into the controller which is actually a part of user interaction. This is a small calculator program that uses has functions one for addition and another for multiplication. Just go through it and I am sure you will find some stuff if you really want to get through this framework.


<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>




Result Value : {{resultNum}}

No comments: