0

我正在构建一个评分系统,并试图根据单独集合中的值计算分数。我一直在使用这个例子:计算 AngularJS ng-repeat 中重复元素的总和,但由于我相信他们使用的是一个集合而不是两个集合,所以无法让它工作。

这是我使用上述问题中的建议的模板:

<div>{{parent.id}}</div>
<div>{{ getTotal() }}</div>
<div ng-repeat="child in children | orderBy: '-postedTime' | filter: {parentId: parent.id}">
  <div>{{child.score}}</div>
</div>

js:

$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.children.length; i++){
    var score = $scope.child.score[i];
    total += (child.score);
}
return total;
}

有没有办法将过滤后的孩子的所有分数相加并显示在父母身上?

4

2 回答 2

0

为简单起见,您可以为要查找的总和添加一个 ng-init

<div ng-repeat="child in children | orderBy: '-postedTime' | filter: {parentId: parent.id}">
<td ng-init="totalScore = totalScore + child.score ">{{totalScore}</td>    
</div>

也许您可以使用 totalScore 来显示您需要的位置

于 2017-01-21T01:51:29.857 回答
0

您可以采取过滤器响应

ng-repeat="child in children | filter: {parentId: parent.id} as kids"

在您的孩子过滤器中使用 as 语法并将其用于总和过滤器,该过滤器将显示父母所有孩子的分数总和。

var app = angular.module('plunker', []);

angular.module('plunker')
  .controller('MainCtrl', function($scope) {


    $scope.totalScore = 0;

    $scope.parents = [{
      id: 1
    }, {
      id: 2
    }]

    $scope.children = [{
      parentId: 1,
      score: 25
    }, {
      parentId: 1,
      score: 25
    }, {
      parentId: 1,
      score: 25
    }, {
      parentId: 2,
      score: 25
    }];

  })


app.filter('sum', function() {
  return function(kids) {
    var total = 0;
    if (kids) {
      for (i = 0; i < kids.length; i++) {
        total = total + kids[i].score;
      };
    }
    return total;
  };
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <link data-require="bootstrap-css@3.3.6" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
  <script data-require="ui-bootstrap@*" data-semver="1.3.2" src="https://cdn.rawgit.com/angular-ui/bootstrap/gh-pages/ui-bootstrap-tpls-1.3.2.js"></script>
  <script src="app.js"></script>
  <script src="accounts.js"></script>
  <script src="controller.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div ng-repeat="parent in parents">
    <div>parent id : {{parent.id}}</div>
    <div>total child scores : {{ kids | sum }}</div>
    <div ng-repeat="child in children | filter: {parentId: parent.id} as kids">
      <div>child Scores : {{child.score}}</div>
    </div>
  </div>


</body>

</html>

PS:我没有父母和孩子的确切 JSON,所以我删除了 children 中的 postedTime,但你可以在你的实际代码中使用它。

于 2017-01-21T02:44:50.527 回答