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

时间:2015-01-28 11:19:15

标签: javascript angularjs angularjs-ng-repeat

我正在使用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}}存储为变量(可能是&#39; itemTotal&#39;)然后将它们一起添加到类似于&#39; orderTotal&#39;并在页面上显示?

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

$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
);

}

非常感谢任何帮助。

感谢。

1 个答案:

答案 0 :(得分:0)

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

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

如果您的$scope.curOrder.partTotal变量尚未初始化,则向undefined添加一个号码会为您提供NaN结果。