famadori
famadori

Reputation: 85

AngularJs ngrepeat The total amount is not being calculated correctly

I'm trying to make a total per line which adds the value of anteior line, more is being added several times. :: I've used and still repeat the run several times.

Example.

code     value   sum
1          2.0      2.0
2          4.0      6.0
3         -2.0      4.0

$scope.calcularTotal = function (dVlLancamento) {
    $scope.dVlTotalAnterior = $scope.dVlTotalAnterior + dVlLancamento;
    return $scope.dVlTotalAnterior;
}


<tr ng-repeat="item in ::rowCollection">
<td>{{::calcularTotal(item.dVlLancamento) | currency}}</td>
</tr>

Only by doing so the value is not right. Sum several times. Can anyone help me?

Upvotes: 0

Views: 36

Answers (1)

Peter Ashwell
Peter Ashwell

Reputation: 4302

You can't guarantee how often your ng-repeat is run, and how many times $scope.dVlTotalAnterior will get the values inside the data structure added to it.

The problem is you are relying on what should be read-only operations, "presentation" operations, to modify the data on your scope ($scope.dVlTotalAnterior). This is bad practice and is why you are getting confusing results.

Try a different approach, here is a plunkr:

http://plnkr.co/edit/GrkXKwuYcW0xXF4oBotb?p=preview

The key is that you do the data manipulation at least in the controller (NOT in the view):

  $scope.rowCollection = [{
    dVlLancamento: 10
  }, {
    dVlLancamento: 20
  }, {
    dVlLancamento: 35
  }];

  // Add subtotals to data
  var sum = 0;
  $scope.rowCollection.forEach(function(elem) {
    sum += elem.dVlLancamento;
    elem.subtotal = sum;
  })

If you don't like modifying the data, then I would suggest a function in your scope that returns a new piece of data with subtotals added.

Upvotes: 1

Related Questions