項目需求,添加列表可拖拽排序功能,谷歌了一下,找到一個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>效果:

我又另外添加了數據排序功能,不能直接使用orderBy篩選器,這樣每次移動都會重新排序,需要使用orderByFilter和$watchCollection來實現效果,具體可查看地址:https://github.com/justforuse/Pro_Angular-demo/tree/master/draggable-list
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答