如何使用AngularJS对子文档中的项目进行分组和计算总和

How to group and calculate the total sum of items in subdocuments using AngularJS

我在我的应用程序中使用 MEAN 堆栈,AngularJS 作为我的前端。我正在尝试获取我的子文档的总和,但没有得到想要的结果。我的 fiddle

我得到的结果

Summary:
1000
100
50
100
100
Total:undefined

我期待的结果

Summary:
1000
100
50
100
100
Total:1350

HTML

<ul>
    <li ng-repeat="mani in items">
      <p ng-repeat ="rohit in mani.colorshades ">
      {{rohit.order_quantity}}
      </p>
    </li>
    <p class="length">Total:{{items.length}}</p>
</ul>

控制器

$scope.items = [{
"_id": "56f91708b7d0d40b0036bc09",
"colorshades": [
    {
    "_id": "56f9177fb7d0d40b0036bc0c",
    "order_quantity": "1000",
    },
    {
    "_id": "56f9177fb7d0d40b0036bc0b",
    "order_quantity": "100",
    },
    {
    "_id": "56f919d7b7d0d40b0036bc13",
    "order_quantity": "50",
    }]
},
{
"_id": "56f367e6a7d3730b008d296a",
"colorshades": [
    {
      "_id": "56f3680ba7d3730b008d296c",
      "order_quantity": "100",
    }
]
},
{
"_id": "56e7af485b15b20b00cad881",
"colorshades": [
    {
    "_id": "56e7af7b5b15b20b00cad882",
    "order_quantity": "100",
    }
]
}];

$scope.getTotals = function () {
    var total = 0;
    for (var i = 0; i < $scope.item.colorshades.length; i++) {
        var item = $scope.item.colorshades[i];
        total += (item.order_quantity);
    }
    return total;
};

我的fiddle

没有直接的方法可以计算总订单数量。您需要有一个控制器方法来计算它,html 可以将它指向该方法或存储总量的 $scope 变量

你有一个两级循环,代码应该是这样的(不要忘记用 parseInt 转换字符串,否则你会有一个连接):

$scope.getTotals = function () {
var total = 0;
for (var i = 0; i < $scope.items.length; i++) {

    for (var j = 0; j < $scope.items[i].colorshades.length; j++) {
      total += parseInt(($scope.items[i].colorshades[j].order_quantity));
    }
}
return total;
};

应该可行:

$scope.getTotals = function () {
var total = 0;
for(var i = 0; i < $scope.items.length; i++) {
  var item = $scope.items[i].colorshades;
  for(var j = 0; j < item.length; j++) {
    total = total + parseInt(item[j].order_quantity);
   }
  }
  return total;
 };
}