kennechu kennechu - 6 months ago 20
Javascript Question

Function to sum value of a specific field from ng-repeat

I want to create a function to sum the value of a specific property coming from a web service in json.

This is my function:

$scope.exportData = data;

$scope.totalLW = function() {
$scope.total=0;

for (var i =0; i < $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW.length; i++) {
$scope.total += parseFloat($scope.exportData.result.merchMetrics.SALES_AMOUNT_LW);
}

return $scope.total;
}


In my view I call the function like this

<td ng-class = "{'positive':totalLW() >= 0, 'negative': totalLW()}">{{totalLW()}}</td>


But I'm getting an
undefined
in my view, I'm sure my function is wrong so I need some help to figure out what is wrong.

$scope.exportData
is working because I have a table and the binding is working fine.

Screenshot.

enter image description here

Answer

I see that You forget using array values in for loop.

 $scope.totalLW = function (){
          $scope.total=0;
          for(var i =0; i < $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW.length; i++ ) {

         $scope.total += parseFloat($scope.exportData.result.merchMetrics.SALES_AMOUNT_LW**[i]**);
       }
       return $scope.total;
    }

And Yes , finally found that point that you miss. You should loop through
for (var i =0; i <$scope.exportData.result.length; i++) on $scope.exportData.result not on $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW

Comments