【发布时间】:2014-01-08 14:31:36
【问题描述】:
我创建了一个自定义指令,允许我使用 Angular js 和 jquery ui 通过拖放连接多个可排序列表。它的工作方式如下:
- 开始拖动时,跟踪项目在数组中的初始位置以及该可排序项的 ng-model 值
- 当拖动结束时,如果项目被接收到不同的列表,请跟踪该列表的 ng-model 和元素的目标位置
- 使用该数据广播事件,以便控制器可以将项目的位置从一个数组更改为另一个数组
问题是,一旦我将一个项目从一个列表移动到另一个列表,即使数组中的项目去到它们应该去的地方,在视图中一些 HTML 元素也会消失。
这是可排序的指令:
app.directive('mySortable',function(){
return {
link:function(scope,el,attrs){
var options = {};
if(attrs.connectWith)
{
options.connectWith = attrs.connectWith;
}
el.sortable(options);
el.disableSelection();
el.on("sortstart", function(event, ui){
var from_index = angular.element(ui.item).scope()?angular.element(ui.item).scope().$index : 0;
var from_model = angular.element(ui.item.parent()).attr('ng-model');
ui.item.scope().sortableData = {from_index: from_index, from_model: from_model};
});
el.on("sortreceive", function(event, ui){
ui.item.scope().sortableData.to_index = el.children().index(ui.item);
ui.item.scope().sortableData.to_model = angular.element(el).attr('ng-model');
});
el.on( "sortdeactivate", function( event, ui ) {
var to_model = angular.element(el).attr('ng-model');
var from = angular.element(ui.item).scope()?angular.element(ui.item).scope().$index : 0;
var to = el.children().index(ui.item);
if(to>=0){
scope.$apply(function(){
if(from>=0){
scope.$emit('list-sorted', {from:from,to:to}, ui.item.scope());
}else{
scope.$emit('list-appended', {to:to, name:ui.item.text()});
ui.item.remove();
}
})
}
} );
}
}
})
这是处理它的事件的控制器逻辑:
$scope.$on('list-sorted', function(ev, val, task_scope){
var sd = task_scope.sortableData;
if(sd.to_model)
{
$timeout(function(){
$scope[sd.to_model].splice(sd.to_index, 0, $scope[sd.from_model].splice(sd.from_index, 1)[0]);
});
}
else
{
$timeout(function(){
$scope[sd.from_model].splice(val.to, 0, $scope[sd.from_model].splice(val.from, 1)[0]);
});
}
console.log($scope);
});
怎么了?
【问题讨论】:
标签: jquery-ui angularjs angularjs-directive