Krishnam
Krishnam

Reputation: 45

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>

Upvotes: 0

Views: 79

Answers (2)

Meet Patel
Meet Patel

Reputation: 510

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>

Upvotes: 1

georgeawg
georgeawg

Reputation: 48968

Use the ng-change directive:

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.a = $scope.b = $scope.sum = 0;
    $scope.updateSum = function() {
        $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>
    A=<input ng-model="a" ng-change="updateSum()" type="number"><br>
    B=<input ng-model="b" ng-change="updateSum()" type="number"><br><br>
    Sum=<input ng-model="sum">
  </form>
</div>

</body>
</html>

Upvotes: 1

Related Questions