我在以AngularJS为前端的应用程序中使用MEAN堆栈。我正在尝试获取子文档的总和,但没有得到理想的结果。我的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>

Controller
$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

最佳答案

您有两个级别的循环,代码应该是这样的(不要忘了通过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;
};

关于javascript - 如何使用AngularJS对子文档中的项目总和进行分组和计算,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36301776/

10-09 15:04