【问题标题】:How to group and calculate the total sum of items in subdocuments using AngularJS如何使用 AngularJS 对子文档中的项目进行分组和计算总和
【发布时间】:2016-07-18 00:57:45
【问题描述】:

我在我的应用程序中使用 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 用于显示内容和交互,JS 用于执行代码。你需要在JS中执行代码来计算总和,也许你应该从一个JS基础指南开始
  • 已更新我的控制器并尝试获取总数
  • 干得好!现在显示您的函数的结果,因此将{{items.length}} 更改为{{getTotals()}}
  • 我有但无法得到答案,所以请看看我的小提琴......
  • 抱歉,看来你真的不知道如何用 JS 编写代码。你有一个$scope.items 数组,里面有包含对象数组的对象。您需要至少 2 个周期才能获得该总和,但您需要知道如何循环数组并正确获取属性...您应该真正从基础开始,否则您将无法获得结果(:

标签: javascript angularjs grouping meanjs


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 已更新我的控制器并尝试获取总数
    【解决方案3】:

    应该可以的:

    $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;
     };
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多