kennechu kennechu - 1 year ago 133
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() {

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

return $;

In my view I call the function like this

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

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

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


enter image description here

Answer Source

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

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download