gpt4 book ai didi

javascript - 使用javascript对表的所有列进行排序的通用函数

转载 作者:行者123 更新时间:2023-11-30 14:51:48 25 4
gpt4 key购买 nike

我的 Controller 中有以下对象数组

$scope.records = [
{
"fName" : "Alfreds",
"lName" : "Berglunds",
"country" : "Germany",
"age":21
},
{
"fName" : "Berglunds",
"lName" : "Alfreds",
"country" : "Sweden",
"age":22
},
{
"fName" : "Centro",
"lName" : "Ernst",
"country" : "Mexico",
"age":23
},
{
"fName" : "Ernst",
"lName" : "Centro",
"country" : "Austria",
"age":24
}
]

我正在使用上面的数组在我的 View 中填充一个表

<table ng-controller="myCtrl" border="1">
<th ng-click="sortByFirstName()">First Nmae</th>
<th ng-click="sortByLastName()">Last Name</th>
<th ng-click="sortByCountry()">Country</th>
<th ng-click="sortByAge()">Age</th>

<tr ng-repeat="x in records">
<td>{{x.fName}}</td>
<td>{{x.lName}}</td>
<td>{{x.country}}</td>
<td>{{x.age}}</td>
</tr>
</table>

单击每个列标题时,我需要按升序对记录进行排序,再次单击它应该翻转排序顺序(降序)。现在我正在使用单独的函数对它们进行排序。谁能建议一种更好的方法来实现同样的目标?类似于使用通用排序函数

最佳答案

您可以通过将 sortBy 作为参数传递给功能

演示

var app = angular.module('testApp',[])

app.controller('myCtrl',function($scope,$filter){
$scope.sortBy = function(sortBy){
$scope.records = $filter('orderBy')($scope.records, sortBy);
}
$scope.records = [
{
"fName" : "Alfreds",
"lName" : "Berglunds",
"country" : "Germany",
"age":21
},
{
"fName" : "Berglunds",
"lName" : "Alfreds",
"country" : "Sweden",
"age":22
},
{
"fName" : "Centro",
"lName" : "Ernst",
"country" : "Mexico",
"age":23
},
{
"fName" : "Ernst",
"lName" : "Centro",
"country" : "Austria",
"age":24
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp">
<table ng-controller="myCtrl" border="1">
<th ng-click="sortBy('fName')">First Nmae</th>
<th ng-click="sortBy('lName')">Last Name</th>
<th ng-click="sortBy('country')">Country</th>
<th ng-click="sortBy('age')">Age</th>

<tr ng-repeat="x in records">
<td>{{x.fName}}</td>
<td>{{x.lName}}</td>
<td>{{x.country}}</td>
<td>{{x.age}}</td>
</tr>
</table>
</body>

关于javascript - 使用javascript对表的所有列进行排序的通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48007950/

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