基于ng运行总计:重复

时间:2013-08-31 23:31:33

标签: javascript angularjs

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

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

1 个答案:

答案 0 :(得分: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;
};

SNIP:

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