I have a problem with Angular.js.
I'm trying to build a simple invoice web app...
When editing invoices, the user should be able to insert and delete new items.
Each item has a readonly field which is the subtotal (unit price * qty) which is calculated by the function calcSubTotal(row)
At the end of the invoice, there is the GrandTotal, calculated by the function calcGrandTotal()
Ex:
HTML:
<div data-ng-repeat='row in rows'>
Unit Price: <input type='text' name='price' data-ng-model='row.unit_price' />
Qty: <input type='text' name='qty' data-ng-model='row.qty' />
<input type='text' readonly value='{{ calcSubTotal(row) }}' />
</div>
<p>GRAND TOTAL: {{ calcGrandTotal() }}</p>
JS (EDIT):
$scope.calcSubTotal = function(row) {
console.log(row);
return (row.unit_price * row.qty);
}
$scope.calcGrandTotal = function() {
var total = 0.00;
$($scope.rows).each(function(i, row) {
var x = $scope.calcSubTotal(row);
total += x || 0.00;
});
return total;
};
Now if I put console.log("CALLED") inside the calcGrandTotal() function I see that it is being called lots of times.
EDIT:
Worst, if I put console.log(row) in the calcSubTotal(row) function, I can see that it is being called for all of the items even when I'm modifying a single item in the invoice.
I mean, if I modify item 1, it shouldn't recalculate item 2 but only update the grand total (based on the previously calculated subtotal for item 2, which hasn't changed...)
How can I optimize this thing?
Thanks.