【发布时间】:2015-02-10 18:48:17
【问题描述】:
在将 jquery sortable 与 angular ng repeat 指令结合使用时,我遇到了意外的行为。我正在尝试对表中不同列中的项目进行排序。
当我将第 2 列的第一个元素拖到第 1 列的第 1 个位置(或第 2 个位置)时 - 一切正常,但如果我尝试将第 2 列的第一个元素放到第 3 或第 4 个位置,它只是与后续元素一起消失。
如果您查看文档底部的 json 编码数组,您会发现组件已正确排序。
如果能提供任何帮助,我将不胜感激。
这里是实时示例:http://plnkr.co/edit/j6xMb4vhcUDVk8POjzpW?p=preview
HTML
<div data-ng-app="myApp" data-ng-controller="defaultCtrl">
<table border="1" data-dnd-list="doc">
<tr>
<td data-ng-repeat="column in doc.columns" data-index="{{$index}}" class="column">
<table class="item" style="border:1px solid red; cursor: pointer" width="100%" data-ng-repeat="component in column.components" data-index="{{$index}}">
<tr>
<td style="padding:5px">{{ component.content }}</td>
</tr>
</table>
</td>
</tr>
</table>
{{ doc }}
</div>
JS
var app = angular.module("myApp", []);
app.controller("defaultCtrl", ["$scope", function($scope) {
$scope.doc = {
columns: [
{
components: [
{
content: "1 column 1 component"
},
{
content: "1 column 2 component"
},
{
content: "1 column 3 component"
}
]
},
{
components: [
{
content: "2 column 1 component"
}
]
}
]
}
}]);
app.directive('dndList', function() {
return function(scope, element, attrs) {
var toUpdate;
var oldComponentIndex = -1;
var oldColumnIndex = -1;
scope.$watch(attrs.dndList, function(value) {
toUpdate = value;
console.log("New changes: ", toUpdate);
},true);
$(element[0]).sortable({
items:'.item',
start:function (event, ui) {
var i = $(ui.item);
// on start we define where the item is dragged from
oldComponentIndex = i.attr("data-index");
oldColumnIndex = i.closest(".column").attr("data-index");
},
stop:function (event, ui) {
var i = $(ui.item);
var newComponentIndex = i.index();
var newColumnIndex = i.closest(".column").attr("data-index");
var toMove = toUpdate.columns[oldColumnIndex].components[oldComponentIndex];
toUpdate.columns[oldColumnIndex].components.splice(oldComponentIndex, 1);
toUpdate.columns[newColumnIndex].components.splice(newComponentIndex, 0, toMove);
scope.$apply(scope.doc);
}
})
}
});
【问题讨论】:
标签: angularjs angularjs-ng-repeat jquery-ui-sortable