简体   繁体   中英

Calculating sum of price in AngularJS

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;
    }
}

尝试在for循环外返回selectedTotal。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM