如何根据筛选的 angularjs 中继器中的项目计算值

How do I calculate a value based on items in a filtered angularjs repeater

我正在构建评分系统,并尝试根据单独集合中的值计算分数。我一直在使用这个例子: Calculating sum of repeated elements in 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;
}

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

为简单起见,您可以添加一个 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 来显示您需要的地方

你可以采取过滤器响应

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

在您的 children 过滤器中使用 as 语法,并在总和过滤器中使用它,该过滤器将显示 parent.[=13= 的所有 children 分数的总和]

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>

P.S :我没有 parents 和 children 的确切 JSON 所以我删除了 children 中的 postedTime 但你可以使用它在你的实际代码中。