我正在尝试在页面上显示动态运行总计。我可以填写字段,单击“添加”按钮,它将其添加到页面中并带有正确的运行总计。我添加第二和第三项。运行总计再次正确更新,但是每行的所有运行总计都显示运行总计。我怎样才能解决这个问题?

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

10-08 11:29