Search code examples
htmlangularjsangularjs-scopeangularjs-ng-repeat

Calculate total price in AngularJS


I'm trying to make this code to get the final number of the sum of all detalle.price elements. They are all numbers so I need to sum them and post the final number on sum().

<div id="pedidos_table">
  <div id="pedidos_table_item" ng-repeat="detalle in detalles">
    <p id="pedidos_table_item_name">{{detalle.name}}</p>
    <p id="pedidos_table_item_price">{{detalle.price}}$</p>
  </div>
</div>
<div id="pedidos_table_total">
  <p id="pedidos_table_item_name">TOTAL</p>
  <p id="pedidos_table_item_price">{{sum()}}$</p>
</div>

I've tried doing this:

$scope.sum = function(){
var total = 0;
total += detalle.price;
return total
}

I know there's something missing, but I don't know what.


Solution

  • Invoking your sum method from a <p></p> tag is not a best practice as the digest cycle might trigger it multiple times. You might follow this way to achieve the same. Also playing with angular $scope is not suggested for production environment, hence use this of the controller instance.

    // Code goes here
    (function(angular) {
      angular.module('myApp', []);
    
      angular.module('myApp').controller('MyController', MyController);
    
      MyController.$inject = ['$scope'];
    
      function MyController($scope) {
        var vm = this;
    
        this.product_details = [{
          name: 'XXX',
          price: 25
        }, {
          name: 'YYY',
          price: 30
        }, {
          name: 'ZZZ',
          price: 67
        }];
    
        vm.total = 0;
        vm.sum = sum;
    
        function sum() {
          angular.forEach(vm.product_details, function(key, value) {
            vm.total += key.price
          });
        }
      }
    })(angular);
    <!DOCTYPE html>
    <html ng-app="myApp">
    
    <head>
      <script data-require="[email protected]" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
      <link rel="stylesheet" href="style.css" />
      <script src="script.js"></script>
    </head>
    
    <body ng-controller="MyController as ctrl">
    
      <div ng-repeat="product in ctrl.product_details">
        <p>{{ product.name }}</p>
        <p>{{ product.price }}</p>
      </div>
    
      <button type="button" ng-click="ctrl.sum()">Calculate total</button>
      <input type="text" ng-model="ctrl.total">
    
    </body>
    
    </html>