Using angularjs, how to perform math operations on textboxes and see result as the values are being typed in?
angularjs, frontend, html
Solution
In your code, the calculation of the sum would only be executed once.
You need to add a watch of the scope or bind a function to `ng-change` event in order to keep the sum updated while you change the numbers.
For example, you can do:
<div ng-app="adder" ng-controller="addcontrol">
<table>
<tr>
<th>Value</th><th>Quantity</th>
</tr>
<tr ng-repeat="number in numbers">
<td><input type="text" ng-change="update()" ng-model="number.val"></td>
<td><input type="text" ng-change="update()" ng-model="number.qty"></td>
<td><input type="button" ng-click="deleteNumber($index)" value= "Delete"></td>pp',[]);
</tr>
</table>
<input type="button" ng-click="add()" value="Add new">Result : {{sum}}
</div>
And:
var myapp = angular.module('adder', []);
myapp.controller('addcontrol', function($scope) {
$scope.numbers = [{
val: 100,
qty: 200,
}
];
$scope.add = function() {
$scope.numbers.push({
val: 0,
qty: 0
});
};
$scope.deleteNumber = function(val) {
numbers.splice(val, 1);
$scope.update();
};
$scope.update = function() {
var result = 0;
angular.forEach($scope.numbers, function(num) {
result += (num.val * num.qty);
});
$scope.sum = result;
};
});
Problem
I have an HTML file with 2 textboxes, one for value and the other for quantity. The result text at the bottom multiplies value with quantity and show the result. The intention is to show the sum of all the rows of pairs of textboxes on the screen. To that end, I have an "add new" button which keeps adding additional pairs of textboxes. The first set of textboxes that appear on the HTML, reflect the size of the "numbers" array of objects containing properties "val" and "qty". The same values are bound to the textboxes. However, only the first set of values are added on screen. As I keep adding new textboxes and entering new values, the value of the result should change accordingly, but it simply doesn't. HTML Code ``` <div ng-app="adder" ng-controller="addcontrol"> <table> <tr> <th>Value</th><th>Quantity</th> </tr> <tr ng-repeat="number in numbers"> <td><input type="text" ng-model="number.val"></td> <td><input type="text" ng-model="number.qty"></td> <td><input type="button" ng-click="deleteNumber($index)" value= "Delete"></td>pp',[]); </tr> </table> <input type="button" ng-click="add()" value="Add new">Result : {{sum}} </div> </body> </html> ``` Javascript ``` var myapp = angular.module('adder', []); myapp.controller('addcontrol',function($scope){ $scope.numbers = [ {val:100, qty:200, } ]; $scope.add = function() { $scope.numbers.push({val:0,qty:0}); }; $scope.deleteNumber = function(val) { numbers.splice(val, 1); }; var result=0; angular.forEach($scope.numbers, function(num){ result+=(num.val * num.qty); }); $scope.sum = result; ``` }); What am I doing wrong here?