gpt4 book ai didi

javascript - 使用 AngularJS 的 FILTER 函数计算过滤器中重复元素的总和

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

我有一个显示记录总数的列表,当过滤单个名称时它仍然显示记录总数而不是过滤记录的总数。 <强> TRY HERE

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
name:
<input type="text" ng-model="model_filter">
<hr/>
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in records | filter: model_filter">
<td>{{x.Name}}</td>
<td>{{x.Money | currency}}</td>
</tr>
<tr>
<td>TOTAL</td>
<td>{{Total | currency}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.records = [
{
"Name": "Rodrigo",
"Money": 10
},
{
"Name": "Rodrigo",
"Money": 25
},
{
"Name": "Arnodl",
"Money": 15
},
{
"Name": "Carlos",
"Money": 5
}
]
$scope.Total = 0;
for (var i = 0; i < $scope.records.length; i++) {
$scope.Total += $scope.records[i].Money;
}

});
</script>

</body>
</html>

结果:

enter image description here

带过滤器:

enter image description here

我的问题

enter image description here

最佳答案

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">
name:
<input type="text" ng-model="model_filter">
<hr/>
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in records | filter: model_filter">
<td>{{x.Name}}</td>
<td>{{x.Money | currency}}</td>
</tr>
<tr>
<th>TOTAL</th>
<td>{{Total()}}</td>
</tr>
<tr>
<th>TotalFiltered</th>
<td>{{ TotalFiltered() }}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [{
"Name": "Rodrigo",
"Money": 10
},
{
"Name": "Rodrigo",
"Money": 25
},
{
"Name": "Arnodl",
"Money": 15
},
{
"Name": "Carlos",
"Money": 5
}
]
$scope.Total = () => $scope.records.reduce((total, b) => total + b.Money, 0);
$scope.TotalFiltered = () => {
return $scope.records.reduce((total, b) => {
if ($scope.model_filter && b.Name.toUpperCase().includes($scope.model_filter.toUpperCase())) { return total + b.Money; }
else { return total; }
}, 0);
}
});
</script>

</body>

</html>

关于javascript - 使用 AngularJS 的 FILTER 函数计算过滤器中重复元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528121/

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