javascript - Angular js : ng-repeat - how to update total sum of list created using ng-repeat?

标签 javascript angularjs angularjs-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 文件中

最佳答案

请参阅更新的链接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;
   });
};

关于javascript - Angular js : ng-repeat - how to update total sum of list created using ng-repeat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45498832/

相关文章:

javascript - Node.js 聊天机器人生成相同的随机数?

javascript - Angular 形式在范围内不可用

javascript - 带有 angularjs 的 Internet Explorer 中的 Blob url

javascript - Angular-material flex 不执行任何操作

javascript - 带有简单数组的基本 ng-repeat

javascript - 具有数组长度条件的 Angular ng-repeat

javascript - 拖放原型(prototype)?

php - foreach 用于 javascript,json 数组

javascript - 如何与 RequireJS 共享全局变量/对象

javascript - 从自定义指令访问 ng-repeat 索引值