Add value with Angularjs no ng-repeat

Asked

Viewed 1,123 times

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, ie make a total, like this:

total += gasto.valor

How’s the right way to do it?

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 dynamicity of Javascript and create a variable in the view itself using the 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>

<div ng-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 filter currency when working with values. This will make it possible to work with internationalization and decimal places.

In the view, it would look something like

{{ ctrl.totalGasto | currency }}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.