0

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>

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.