Millenial2020
Millenial2020

Reputation: 2913

Angular ng-repeat how do i add sums

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

Answers (3)

CozyAzure
CozyAzure

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

Suresh B
Suresh B

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

Sreehari S
Sreehari S

Reputation: 388

Try

<td>{{item.price +=items[$index-1].price}}</td>

Upvotes: 0

Related Questions