嵌套ng-repeat中的聚合

时间:2015-08-02 23:50:25

标签: javascript angularjs ng-repeat

我想创建每个taskAssembly对象的taskAssembly.labour的总和并将其放在totalLabour字段中

看到这个plunker。 http://plnkr.co/edit/rKnup0IIPRYvh8JLHXbD?p=preview

查看我的数据:

{ "client": "client1","takeoff": [{
"taskName": "ToW",
 "taskQnt": 2300,
"totalLabour":"",
"taskAssembly": [
  {
    "taskName": "ToW",
    "taskQnt": 2300,
    "taskLabour": 22,
    "taskAssembly": [
  { "qnt": 2300, "product": "non-INT", "labour": 12, "application":      "spray" },
  { "qnt": 2300, "product": "non-INT", "labour": 10, "application": "strips" }
    ]
  },
      {
       "taskName": "Pens",
       "taskQnt": 43,
        "taskLabour": 23,
        "taskAssembly": [
           { "qnt": 43, "product": "non-INT", "labour": 23, "application": "spray" }
           ]
       }
    ]}

我的代码并不完全符合我的需要。

      $scope.getTotalLabour = function(){
    var total = 0;
    for(var i = 0; i < $scope.estimate.takeoff.length; i++){
      var item = $scope.estimate.takeoff[i];
      total += (item.taskLabour);
    }
    return $scope.estimate.totalLabour = total;
  }

我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

检查工作演示:JSFiddle

只需创建一个嵌套循环,如:

for(var i = 0; i < $scope.estimate.takeoff.length; i++){
  var total = 0;
  var item = $scope.estimate.takeoff[i];
  console.log(item);
  for (var j = 0; j < item.taskAssembly.length; j++) {
    total += (item.taskAssembly[j].labour);
  }
  item.totalLabour = total;
}