计算 ng-repeat Angular JS 表达式的总数

Calculating total of ng-repeat Angular JS expression

本文关键字:表达式 JS ng-repeat Angular 计算      更新时间:2023-09-26

我正在使用Angular构建报价系统。我显示了不同的项目,但我正在努力生成总成本。请参阅下面的代码:

<tr ng-repeat="part in curOrder.orderParts">
    <td>{{part.partDesc}}</td>
    <td>{{part.partQty}}</td>
    <td>{{part.partPrice * part.partQty | number:2}}</td>
</tr>
<tr>
    <td>&nbsp;</td>
    <th>Total</th>
    <td>
        {{(part.partPrice * part.partQty)*(curOrder.orderParts.length) | number:2}}&nbsp;{{curOrder.currency}}
        //I know this line doesn't work as it isn't in the ng-repeat.
        //How would I store this expression as a variable so I could use it here?
    </td>
</tr>

我将如何将 {{part.partPrice * part.partQty}} 存储为变量(可能是"itemTotal"),然后将所有这些将它们加在一起,例如"orderTotal"并将其显示在页面上?

我应该提到,在此过程中,用户可以通过输入字段更改每个零件的价格。这会导致用户更改价格时变量未更新的问题。代码如下:

$scope.orderParts = $scope.curOrder.orderParts;
for($part in $scope.orderParts){
$partTotal = parseInt($scope.orderParts[$part].partQuotePrice * $scope.orderParts[$part].partQty);
$scope.curOrder.partTotal += $partTotal;
console.log(
    "'n partQuotePrice: "+$scope.orderParts[$part].partQuotePrice + //Prints 0 as nothing in user input yet
    "'n partQty: "+ $scope.orderParts[$part].partQty + //Prints 100
    "'n Multipled: "+($scope.orderParts[$part].partQuotePrice * $scope.orderParts[$part].partQty)+ //Prints 0 (0*100)
    "'n partQuotePriceTotal:"+$scope.curOrder.partTotal //Prints NaN
);

}

任何帮助将不胜感激。

谢谢。

您似乎正在使用$scope.curOrder.partTotal += $partTotal; - 您是否曾经将$scope.curOrder.partTotal设置为 0?

x = undefined
x += 2 // x == NaN

如果$scope.curOrder.partTotal变量尚未初始化,则向undefined添加一个数字将得到NaN结果。