我在我的应用程序中使用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
答案 0 :(得分:2)
你有两个级别的循环,代码应该是这样的(不要忘记通过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;
};
答案 1 :(得分:0)
没有可用于计算总订单数量的直接方法。你需要有一个控制器方法来计算它,html可以将它指向那个存储总量的方法或$ scope变量
答案 2 :(得分:0)
这应该有效:
$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;
};
}