Reputation: 2913
I have a sales table that I want loop and add the total as I go. I have something like this.
<h1>Sale</h1>
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.price +=item.price}}</td>
</tr>
This this what I want
<h1>Sale</h1>
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td>Burrito</td>
<td>$2.00</td>
<td>$2.00</td>
</tr>
<tr>
<td>Taco</td>
<td>$1.00</td>
<td>$3.00</td>
</tr>
<tr>
<td>Quesadilla</td>
<td>$4.00</td>
<td>$7.00</td>
</tr>
</table>
How do I add the previous price to the total as my ng-repeat loops thru it.
Upvotes: 0
Views: 42
Reputation: 8468
Have a method that evaluates the subtotal:
$scope.getSubTotal = function(index) {
var subtotal = 0;
for (var i = 0; i < index+1; i++) {
var item = $scope.items[i];
subtotal += item.price;
}
return subtotal;
}
At your table, pass in the index:
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{getSubTotal($index)}}</td>
</tr>
Working Plnkr
Upvotes: 1
Reputation: 1652
total needs only once means in that table use like this...
<td>Total: {{ getTotal() }}</td>
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.items.length; i++){
var item = $scope.items[i];
total += item.price;
}
return total;
}
Upvotes: 0