JSFiddle - React, Tailwind, and code Playground
by Amal Das
HTML
<div ng-controller="SortableCTRL">
<ul id="sortable">
<!--<li ng-repeat="item in sortableArray" ng-bind="item"></li>-->
<li><div class="myHandle"></div>aaa</li>
<li><div class="myHandle"></div>bbb</li>
<li><div class="myHandle"></div>ccc</li>
</ul>
<hr>
<pre ng-bind="sortableArray|json"></pre>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.10/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"></script>
<script>
/*
jQuery UI Sortable plugin wrapper
@param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
*/
angular.module('ui.sortable', [])
.value('uiSortableConfig',{})
.directive('uiSortable', [
'uiSortableConfig', '$timeout', '$log',
function(uiSortableConfig, $timeout, $log) {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
var savedNodes;
function combineCallbacks(first,second){
if(second && (typeof second === 'function')) {
return function(e, ui) {
first(e, ui);
second(e, ui);
};
}
return first;
}
function hasSortingHelper (element) {
var helperOption = element.sortable('option','helper');
return helperOption === 'clone' || typeof helperOption === 'function';
}
var opts = {};
var callbacks = {
receive: null,
remove:null,
start:null,
stop:null,
update:null
};
angular.extend(opts, uiSortableConfig);
if (!angular.element.fn || !angular.element.fn.jquery) {
$log.error('ui.sortable: jQuery should be included before AngularJS!');
...
CSS
li {
padding: 5px;
border: 1px solid #999;
background: #eee;
margin: 5px;
cursor: move;
}
.myHandle {
display: inline-block;
height: 20px;
width: 20px;
vertical-align: middle;
background-color: #000;
cursor: move;
}
JavaScript
function SortableCTRL($scope) {
var sortableEle;
$scope.sortableArray = [
'One', 'Two', 'Three'
];
$scope.dragStart = function(e, ui) {
ui.item.data('start', ui.item.index());
}
$scope.dragEnd = function(e, ui) {
var start = ui.item.data('start'),
end = ui.item.index();
$scope.$apply();
}
sortableEle = $('#sortable').sortable({
start: $scope.dragStart,
handle: '.myHandle',
update: $scope.dragEnd
});
}