athi athi - 4 months ago 10
Javascript Question

Sum in angular js loop

I have an array like this.

$scope.addit=[{name:'A',amt:0},{name:'B',amt:0},{name:'C',amt:10},{name:'D',amt:100}];
$scope.TSUM = 100;

var total_Add = 0;

var amnt =0;
angular.forEach($scope.addit, function(item) {
if(item.name == 'A'){
amnt = $scope.TSUM;

}
else if(item.name == 'B'){
amnt = $scope.TSUM + 10;
}

else if(item.name != 'A' && item.name != 'B' ){
amnt = item.amount;

}

total_Add = total_Add+amnt;

})


My code should return the sum. But here it is concatenating all values.
I get like 10011010100.

Please help me. It is making issue while adding item.amount.

Answer

+ is used for concatenation in javascript, so for addition You have to use eval()

So write your code as follow

 amnt = eval($scope.TSUM +"+ 10");

So it looks like

amnt = eval("20 + 10");