0

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

列表控件

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>
4

1 回答 1

2

您没有在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;
});
于 2013-08-31T23:38:37.813 回答