gpt4 book ai didi

javascript - AngularJS - Angular Filter Group By sum 行

转载 作者:行者123 更新时间:2023-11-29 21:34:11 25 4
gpt4 key购买 nike

我需要按性别汇总所有年龄。要求的结果如下:

enter image description here

但是我只能得到男女所有年龄的总和,请看下面的源代码更详细地了解我想做什么。

JSFiddle Source Code

var demoApp = angular.module("demoApp", ["angular.filter"]);
demoApp.controller("MainController", function($scope) {
$scope.users = [{
id: 1,
name: "Mike",
age: 22,
gender: "Male"
}, {
id: 2,
name: "Joe",
age: 28,
gender: "Male"
}, {
id: 3,
name: "David",
age: 30,
gender: "Male"
}, {
id: 4,
name: "Susan",
age: 25,
gender: "Female"
}, {
id: 5,
name: "Marie",
age: 27,
gender: "Female"
}, {
id: 6,
name: "Julie",
age: 33,
gender: "Female"
}];
$scope.sumByGender = function() {
var total = 0;
for (count = 0; count < $scope.users.length; count++) {
total += $scope.users[count].age;
}
return total;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div ng-app="demoApp" ng-controller="MainController">
<div ng-repeat="(key, value) in users | groupBy: 'gender'">
Gender: {{key}}
<div>
<table class="table table-bordered">
<thead>
<tr>
<td>#</td>
<td>Name</td>
<td>Age</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in value">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="2" class="text-right">Total</td>
<td>{{sumByGender()}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

最佳答案

gender 作为参数传递给您的 sumByGender() 然后在计算总计之前检查每个项目的性别

HTML

{{sumByGender(key)}}

JS

$scope.sumByGender = function(gender) {
// Here I need to sum by gender
var total = 0;
for (var count = 0; count < $scope.users.length; count++) {

if ($scope.users[count].gender == gender) {
total += $scope.users[count].age;
}

}
return total;
}

DEMO

关于javascript - AngularJS - Angular Filter Group By sum 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com