Angularjs 非常擅长处理这些事情的“接线”。这是一个由 Francesco 建议的算法的示例,该算法使用 Angular 控制器来处理项目/分数和表格之间的所有绑定以及处理排序/重新评分的指令:
angular.module("listApp", []).
controller("listController", function($scope) {
var sortByKey = function(arr, key) {
arr.sort(function(a, b) {
if (a[key] > b[key]) {
return -1;
} else if (b[key] > a[key]) {
return 1;
} else {
return 0;
}
});
};
$scope.items = [{id: 1111, name: "Item 1", score:0.2},
{id: 3333, name: "Item 2", score:0.5},
{id: 5555, name: "Item 3", score:0.7}];
sortByKey($scope.items, "score");
}).
directive("sortable", function() {
return function(scope, element) {
var startIndex = null;
var stopIndex = null;
var averageOfNeighbors = function(items, index) {
var beforeScore = index === 0 ? 1 : items[index -1].score;
var afterScore = index === items.length - 1 ? 0 : items[index + 1].score;
return (beforeScore + afterScore) / 2;
}
element.sortable( {
start: function(e, ui) {
startIndex = ui.item[0].sectionRowIndex;
},
stop: function(e, ui) {
stopIndex = ui.item[0].sectionRowIndex;
if (stopIndex !== startIndex) {
var toMove = scope.items.splice(startIndex, 1)[0];
scope.items.splice(stopIndex, 0, toMove);
toMove.score = averageOfNeighbors(scope.items, stopIndex);
console.log("Set item(" + toMove.id + ").score to " + toMove.score);
scope.$apply();
}
}
});
}
})
然后可以将它简单地绑定到这样的表:
<tbody sortable>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{$index + 1}}</td>
<td>{{item.score}}</td>
</tr>
</tbody>
这是一个Plunker。
另外,请注意,在每次重新排序之后,可以进行 AJAX 调用来更新数据库中的单个分数记录。