JSFiddle - React, Tailwind, and code Playground
by Nicolas Lips
HTML
<div ng-app="app">
<table>
<tr>
<th>Liste simple</th>
<th>Drag & Drop</th>
</tr>
<tr>
<td>
<ul ng-controller="simpleController as ctrl">
<li ng-repeat="item in ctrl.items" ng-controller="simpleItemController as itemCtrl">
{{item.name}}
<select ng-model="itemCtrl.rank">
<option ng-repeat="o in ctrl.rankOptions" ng-value="o">{{o}}</option>
</select>
</li>
</ul>
</td>
</tr>
</table>
</div>
JavaScript
angular.module("app", [])
.service("businessLayer", ["$q", "$rootScope", function($q, $rootScope) {
var changeRankPromise = $q.when(true);
var itemList = [];
function addItem(name) {
itemList.push({
name: name
})
}
for (var i=0;i<3;i++) {
addItem(randomString());
}
return {
getItems: function () {
return itemList;
},
moveItem: function(oldRank, newRank) {
// simulate async server
changeRankPromise = changeRankPromise
.then(
setTimeout(function() {
var old = angular.copy(itemList);
angular.copy([], itemList);
var item = old[oldRank];
for (var i=0;i<old.length;i++) {
if (i == newRank) {
itemList.push(item);
}
var s = old[i];
if (s == item) {
continue;
}
itemList.push(s);
}
$rootScope.$digest();
},
1000));
return changeRankPromise;
}
};
}])
.controller("simpleController", ["businessLayer", "$scope", function(businessLayer, $scope) {
var items = businessLayer.getItems();
var rankOptions = [];
$scope.$watchCollection(function () {
return items;
}, function(newCollection, oldCollection, scope) {
angular.copy([], rankOptions);
for (var i=0;i<newCollection.length;i++) {
rankOptions.push(i);
}
});
return {
items: items,
rankOptions: rankOptions
};
}])
.controller("simpleItemController", ["$scope", "businessLayer", function($scope, businessLayer) {
var vm = {};
$scope.$watch(function() {
return $scope.$parent.$index;
}, function(newValue, oldValue, scope) {
vm.rank = ""+newValue;
});
$scope.$watch(function () {
return vm.rank;
}, function(newValue, oldValue, scope) {
if (newValue == oldValue)
{
return;
}
businessLayer.moveItem(scope.$parent.$index, newValue);
});
return...