gpt4 book ai didi

javascript - 基于 ng :repeat 的运行总计

转载 作者:行者123 更新时间:2023-12-02 18:24:04 25 4
gpt4 key购买 nike

我正在尝试在页面上显示动态运行总计。我可以填写字段,单击添加按钮,然后将其添加到具有正确运行总计的页面。我添加第二项和第三项。运行总计再次正确更新,但是每行的所有运行总计都显示总运行总计。我该如何解决这个问题?

ListCtrl

angular.module('MoneybooksApp')
.controller('ListCtrl', function ($scope) {
$scope.transactions = [];

$scope.addToStack = function() {
$scope.transactions.push({
amount: $scope.amount,
description: $scope.description,
datetime: $scope.datetime
});

$scope.amount = '';
$scope.description = '';
$scope.datetime = '';
};

$scope.getRunningTotal = function(index) {
console.log(index);
var runningTotal = 0;
var selectedTransactions = $scope.transactions.slice(0, index);
angular.forEach($scope.transactions, function(transaction, index){
runningTotal += transaction.amount;
});
return runningTotal;
};
});

HTML

<div ng:controller="ListCtrl">
<table class="table">
<thead>
<tr>
<th></th>
<th>Amount</th>
<th>Description</th>
<th>Datetime</th>
<th></th>
</tr>
<tr>
<td><button class="btn" ng:click="addToStack()"><i class="icon-plus"></i></button></td>
<td><input type="number" name="amount" ng:model="amount" placeholder="$000.00" /></td>
<td><input name="description" ng:model="description" /></td>
<td><input name="datetime" ng:model="datetime" /></td>
<td></td>
</tr>
<tr>
<th>Running Total</th>
<th>Amount</th>
<th>Description</th>
<th>Datetime</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng:repeat="transaction in transactions" class="{{transaction.type}}">
<td>{{getRunningTotal($index)}} {{$index}}</td>
<td>{{transaction.amount}}</td>
<td>{{transaction.description}}</td>
<td>{{transaction.datetime}}</td>
<td><button class="btn"><i class="icon-remove"></i></button></td>
</tr>
</tbody>
</table>
</div>

最佳答案

您没有在 foreach 循环中使用变量 selectedTransactions。您的 foreach 循环正在计算 $scope.transactions 中的所有交易。

$scope.getRunningTotal = function(index) {
console.log(index);
var runningTotal = 0;
var selectedTransactions = $scope.transactions.slice(0, index);
angular.forEach($scope.transactions, function(transaction, index){
runningTotal += transaction.amount;
});
return runningTotal;
};

截图:

angular.forEach(selectedTransactions, function(transaction, index){
runningTotal += transaction.amount;
});

关于javascript - 基于 ng :repeat 的运行总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18553773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com