0

I am having trouble with getting the total amount of price when a list of item is selected by the checkbox. With this for loop, all I get is the first two dollar amount (I know it is the selectedTotal += (getAmount.amount + getAmount.amount); problem, but not sure how to fix it), I cannot get total price amount when there are more then three selected list item. tempData is array var tempData = [] Help will be appreciated.

HTML

 <label class="item item-input ">
    <b class="input-label">Total Amount: </b>
    <span style="margin-left:30%;"> ${{getTotal()}} </span>
 </label>

CONTROLLER

$scope.getTotal = function () {
    var selectedTotal = 0;
    for (var i = 0; i < $scope.tempData.length; i++) {
        if ($scope.tempData[i].checked) {
            var getAmount = $scope.tempData[i];
            selectedTotal += (getAmount.amount + getAmount.amount);
        }
        return selectedTotal;
    }
}
2
  • Why do you have selectedTotal += (getAmount.amount + getAmount.amount); (getAmount.amount twice) ? Commented Jul 28, 2015 at 9:35
  • I got it now, I remove the second getAmount.amount and then put the return selectedTotal outside of the forloop at it works now Commented Jul 28, 2015 at 9:40

2 Answers 2

2

You have to put return selectedTotal outside the loop otherwise it will return value after every iteration of the loop.

$scope.getTotal = function () {
    var selectedTotal = 0;
    for (var i = 0; i < $scope.tempData.length; i++) {
        if ($scope.tempData[i].checked) {
            var getAmount = $scope.tempData[i];
            selectedTotal += (getAmount.amount + getAmount.amount);
        }
    }
return selectedTotal;
}

Read here: Return in for loop or outside loop

Sign up to request clarification or add additional context in comments.

Comments

2

Try to return selectedTotal outside of for loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.