作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要按性别汇总所有年龄。要求的结果如下:
但是我只能得到男女所有年龄的总和,请看下面的源代码更详细地了解我想做什么。
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;
}
关于javascript - AngularJS - Angular Filter Group By sum 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35305664/
我是一名优秀的程序员,十分优秀!