Search code examples
htmlangularjsdata-binding

Add 2 input values and display result in another input box


I am new to AngularJS. Want to get values from 2 input text boxes, add them and then display them in a 3rd text box.

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.sum = ( $scope.a + $scope.b );
});
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form>
    <input ng-model="a" type="number">
    <input ng-model="b" type="number">
    <input ng-model="sum" type="number">
  </form>
</div>

</body>
</html>


Solution

  • You can achieve without creating any function just put value = {{a+b}} in you 3rd input tag

    var app = angular.module('myApp', []);
    app.controller('formCtrl', function($scope) {
        $scope.sum = ( $scope.a + $scope.b ); // this will assign value sum only when one time- when controller init happen and that time a and b both is undefined 
    });
    <!DOCTYPE html>
    <html lang="en">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <body>
    
    <div ng-app="myApp" ng-controller="formCtrl">
      <form>
        <input ng-model="a" type="number">
        <input ng-model="b" type="number">
        <input value="{{a + b}}" type="number">
      </form>
    </div>
    
    </body>
    </html>