需求
- 针对list中某个字段,实现list的升序和降序
效果图
代码
我是用在angular1.X中项目的,根据list中的sort字段进行排序。
# sort.html
<style>
.list-sort .upper-sort {
width: 0;
height: 0;
margin-bottom: 10px;
border-top: 15px solid transparent;
border-right: 15px solid transparent;
border-bottom: 15px solid #ccc;
border-left: 15px solid transparent;
}
.list-sort .down-sort {
width: 0;
height: 0;
border-top: 15px solid #ccc;
border-right: 15px solid transparent;
border-bottom: 15px solid transparent;
border-left: 15px solid transparent;
}
</style>
...
<div class="list-sort">
<div class="upper-sort" data-action="upper" ng-click="upSort()"></div>
<div class="down-sort" data-action="down" ng-click="downSort()"></div>
</div>
#sortCtrl.js
function bubble_sort(list) {
count = list.length;
for (let i = 0;i < count - 1;i++) {
let swapped = false;
for (let j = 0;j < count - 1;j++) {
if (list[j].score > list[j + 1].score) {
let temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
return list;
}
function bubble_sort_revert(list) {
count = list.length;
for (let i = 0;i < count - 1;i++) {
let swapped = false;
for (let j = 0;j < count - 1;j++) {
if (list[j].score < list[j + 1].score) {
let temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
return list;
}
$scope.upSort = function () {
bubble_sort($scope.candidateList)
let upper = document.querySelector("[data-action=upper]");
let down = document.querySelector("[data-action=down]");
upper.style.borderBottomColor = "#2196f3";
down.style.borderTopColor = "#ccc";
};
$scope.downSort = function () {
bubble_sort_revert($scope.candidateList)
let upper = document.querySelector("[data-action=upper]");
let down = document.querySelector("[data-action=down]");
upper.style.borderBottomColor = "#ccc";
down.style.borderTopColor = "#2196f3";
};