我正在构建一个评分系统,并尝试根据单独集合中的值计算分数。我一直在使用这个例子:计算 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-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,所以我删除了孩子的postedTime,但您可以在实际代码中使用它。
为了简单起见,您可以为要查找的总和添加一个 ng-init
<div ng-repeat="child in children | orderBy: '-postedTime' | filter: {parentId: parent.id}">
<td ng-init="totalScore = totalScore + child.score ">{{totalScore}</td>
</div>
也许您可以使用总分数来显示您需要它的地方