使用angular-ui-sortable实现可拖拽排序列表

时间:2021-12-17 11:18:05

项目需求,添加列表可拖拽排序功能,谷歌了一下,找到一个Angular的插件:angular-ui-sortable,项目地址:https://github.com/angular-ui/ui-sortable

需要在之前引入jquery,和jquery-ui,否则无法使用。

我们要做的事情,加载数据,拖拽排序并输出当前顺序:

js代码:

<script src="../../jquery.js"></script>
<script src="../../jquery-ui.js"></script>
<script src="../../angular.js"></script>
<script src="ui-sortable/src/sortable.js"></script>
<script>
angular.module("app", ["ui.sortable"])
.controller("sortCtrl", function($scope, $timeout) {
$scope.cannotSort = false;
$scope.data = [{
"name": "allen",
"age": 21,
"i": 0
}, {
"name": "bob",
"age": 18,
"i": 1
}, {
"name": "curry",
"age": 25,
"i": 2
}, {
"name": "david",
"age": 30,
"i": 3
}];

$scope.sortableOptions = {
// 数据有变化
update: function(e, ui) {
console.log("update");
//需要使用延时方法,否则会输出原始数据的顺序,可能是BUG?
$timeout(function() {
var resArr = [];
for (var i = 0; i < $scope.data.length; i++) {
resArr.push($scope.data[i].i);
}
console.log(resArr);
})


},

// 完成拖拽动作
stop: function(e, ui) {
//do nothing
}
}
})
</script>

html代码:

<body>
<div ng-controller="sortCtrl">
<ul ui-sortable="sortableOptions" ng-model="data">
<li ng-repeat="item in data ">
<span>
{{item.name}}, {{item.age}}</span>
</li>
</ul>
</div>
</body>

效果:

使用angular-ui-sortable实现可拖拽排序列表

我又另外添加了数据排序功能,不能直接使用orderBy筛选器,这样每次移动都会重新排序,需要使用orderByFilter和$watchCollection来实现效果,具体可查看地址:https://github.com/justforuse/Pro_Angular-demo/tree/master/draggable-list