How to display sum of two textbox in third textbox in AngularJS

This is the very common requirement to display sum of the two textbox input controls in the third textbox. However, there are many ways to display the sum of the two into the third input control using Angular but the correct implementation is depend on your requirement.

I am assuming that there are two input(‘number’ type) controls and I want to show their sum into third read only number type input control.

First see the html code:

<body ng-controller="MainCtrl">
  <p> Add the Numbers</p>
  <p>
    <input type="text" ng-model="val1" ng-change="updateSum()"> +
    <input type="text" ng-model="val2" ng-change="updateSum()"> =
    <input type="text" disabled ng-model="sumVal">
  </p>
</body>

We are using the ‘ngChange’ directive which will triger the updateSum() method immidiately after changing the input value. Both input controls shares the same event handler.

var app = angular.module('plunker', []);
 
app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.updateSum = function() {
    $scope.sumVal = ($scope.val1 * 1) + ($scope.val2 * 1);
  }
});

You can run the the above example on the Plunker.

Author: Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.