Angularjs : ng-repeat - 如何更新使用 ng-repeat 创建的列表的总和?

Angularjs : ng-repeat - how to update total sum of list created using ng-repeat?

我是 angularjs 的新手,正在尝试创建一个非常简单的页面,我在其中显示产品、价格、数量、小计(价格 * 数量)和总金额。我想,如果用户更新数量,那么小计和总和应该实时更新。我试过但无法得到它。 像这样尝试:

<body ng-app="myApp" ng-controller="myCtrl">

<table class="table table-bordered table-hover">
  <thead>
    <tr>
      <th>Product</th>
      <th>Price</th>
      <th>Quantity</th>
      <th>Price * Quantity</th>
    </tr>
  </thead>
  <tbody ng-init="total = 0">
    <tr ng-repeat="product in products">
      <td>{{ product.name }}</td>
      <td>{{ product.price }}</td>
      <td><input value="{{ product.quantity }}"></td>
      <td ng-init="$parent.total = $parent.total + (product.price * product.quantity)">${{ product.price * product.quantity }}</td>
    </tr>
    <tr>


      <td><b>Total</b></td>
      <td></td>
      <td></td>
      <td><b>${{ total }}</b></td>
    </tr>
  </tbody>
</table>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  var i = 0;
  $scope.products = [
    {
      "name": "Product 1",
      "quantity": 2,
      "price": 10
    },
    {
      "name": "Product 2",
      "quantity": 6,
      "price": 8
    },
    {
      "name": "Product 3",
      "quantity": 5,
      "price": 26
    },
    {
      "name": "Product 4",
      "quantity": 10,
      "price": 4
    },
    {
      "name": "Product 5",
      "quantity": 11,
      "price": 7
    }
    ];
});
</script>
</body>

这是我到目前为止的全部代码:http://plnkr.co/edit/QSxYbgjDjkuSH2s5JBPf?p=preview

提前致谢!

注意 :我想用 angular 方式做所有这些事情,即仅在 HTML 中。此数据脚本将放入 .js 文件

只要做一个函数,每次更改值时都计算总数

table正文Html

<tbody ng-init="total = 0">
    <tr ng-repeat="product in products">
      <td>{{ product.name }}</td>
      <td>{{ product.price }}</td>
      <td><input ng-change="updateTotal()" ng-model="product.quantity"></td>
      <td>${{ product.price * product.quantity }}</td>
    </tr>
    <tr>
      <td><b>Total</b></td>
      <td></td>
      <td></td>
      <td><b>${{ total }}</b></td>
    </tr>
  </tbody>

并在JS中添加一个函数

$scope.updateTotal = function(){
      $scope.total = 0;
    for(product of $scope.products){
       $scope.total += product.quantity * product.price
    }
  }

有求总数的功能,

   $scope.getTotal = function() {
        var total = 0;
        for (var i = 0; i < $scope.products.length; i++) {
          var product = $scope.products[i];
          total += (product.price * product.quantity);
        }
        return total;
      }

数量变化时调用函数,

<td>
 <input ng-model="product.quantity" ng-change="getTotal()">
</td>

DEMO

请参考更新link http://plnkr.co/edit/HOCVZC2p3xfG2apoKJDW?p=preview 您没有计算总数的功能。您需要添加它并在更改任何数量文本框时调用该函数。 您还需要为数量 ng-change="updateTotal()"

的所有文本框添加更改事件
$scope.updateTotal = function(){
    $scope.total = 0;
    angular.forEach($scope.products, function(product){
       $scope.total += product.quantity*product.price;
   });
};