Search code examples
angularjsangular-controller

summing up number of angular.foreach loop


I'm trying to sum ups a few numbers in what should be a simple function. I iterate through my list of numbers and can see form the log that I am seeing each number.

Then I have the following where I have a var that holds the sum and should return it.

But nothing happens!

Here is the code:

  angular.extend(self, {

    getTotalGood : function(){
      var total = 1;
      angular.forEach( self.myproducts, function( value, key ){
        console.log(key + ' : ' + value.product.cost);
        total = value.product.cost;
      })
      return total;
    }

  })

  self.getTotalGood();

Solution

  • Change your method like below:

     getTotalGood : function(){
      var total = 0;
      angular.forEach( self.myproducts, function( value, key ){
        console.log(key + ' : ' + value.product.cost);
        total += value.product.cost;
      })
      console.log("total: " + total);
      return total;
    }