Add value with angularjs in ng-repeat

3

I have the following code:

<li ng-repeat="gasto in gastos">
    R${{ gasto.valor }} - {{ gasto.descricao }}
</li>

This prints on the screen the expenses and the description, but I would like to add the expenses, that is to make a total, like this:

total += gasto.valor

How is the right way to do it?

    
asked by anonymous 08.02.2017 / 03:01

1 answer

4

There are several ways to do this.

If you just want to show the value in the view, you can take advantage of the dynamics of JavaScript and create a variable in the view itself using ng-init .

Example:

angular.module('myApp', []);

angular.module('myApp').controller('mainController', mainController);

function mainController($scope){  
  this.gastos = [{ valor: 1, descricao: 'Gasto 1' }, 
                 { valor: 2, descricao: 'Gasto 2' }, 
                 { valor: 3, descricao: 'Gasto 3' }];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp">
  <div ng-controller="mainController as ctrl">
    <li ng-repeat="gasto in ctrl.gastos" ng-init="ctrl.totalGasto = ctrl.totalGasto + gasto.valor">
      R$ {{gasto.valor }} - {{ gasto.descricao }}
    </li>
    <br>
    Total: R$: {{ctrl.totalGasto}}
  </div>
</div>

Tip

You can use the currency filter when working with values. This will make it possible to work with internationalization and decimals.

In the view, it would look something like

{{ ctrl.totalGasto | currency }}
    
08.02.2017 / 03:09