我正在尝试从jQuery重新创建可分类的可排序功能,并且无法将删除的元素放入我的对象数组中.
我想拖动一个$.draggable()按钮到一个$.sortable()列表..我希望按钮表示一个对象与属性(可以是assoc数组或对象本身),当我把它放在我的列表我想让它把它放在阵列的位置被放下.
只是为了清楚:我在左边的菜单中有一系列潜在的对象.在右边,我使用$http调用我的API来检索一个表单,其中的所有字段都保存在$scope中.我想要将该潜在对象(如textarea)放入该表单的字段中.
jquery位是直接的,但是在$scope数组中定位的不存在的对象是问题.
我试过的
我很喜欢混合使用ui-sortable和$.draggable指令包装,但我的代码不能很好地工作.
例子:
> KnockoutJS示例:http://bit.ly/15yrf8X
> jQuery demo:http://jqueryui.com/draggable/#sortable
更新1:
我已经取得了进步与一个ui可排序的指令结合一个指令,包裹$.draggable(),有点丑陋,但工作.
更新2:
我现在有工作,但是我从jquery抓取索引,并使用PHP将其分割到该位置,然后重新加载整个列表.谈论跛脚,必须有一个更好的方法.
更新3:
这是一个模块化的任何人的应用程序的工作示例.
http://clouddueling.github.io/angular-common
解决方法
http://plnkr.co/edit/aSOlqR0UwBOXgpQSFKOH?p=preview
<ul>
<li my-draggable="#sortable" class="ui-state-highlight">Drag me down</li>
</ul>
<ul my-sortable id="sortable">
<li class="ui-state-default" ng-repeat="item in items">{{item.name}}</li>
</ul>
我的draggable的值是相应的my-sortable-element的id.我的拖曳是非常简单的:
app.directive('myDraggable',function(){
return {
link:function(scope,el,attrs){
el.draggable({
connectToSortable: attrs.myDraggable,helper: "clone",revert: "invalid"
});
el.disableSelection();
}
}
})
在我的排序中,我听取了deactivate事件,表示元素已被删除. from是作为ng重复源的数组中的元素的位置. ng-repeat为每个元素创建一个子索引变量,该索引变量指示数组中当前元素的位置.如果$index是未定义的,我知道它是一个新元素(可能是更好的方式来确定这个,但它适用于此示例).是项目的新位置.如果现有元素被移动,或者如果添加了新项目,我将发出“我的排序”事件或“我创建的”事件.
app.directive('mySortable',function(){
return {
link:function(scope,attrs){
el.sortable({
revert: true
});
el.disableSelection();
el.on( "sortdeactivate",function( event,ui ) {
var from = angular.element(ui.item).scope().$index;
var to = el.children().index(ui.item);
if(to>=0){
scope.$apply(function(){
if(from>=0){
scope.$emit('my-sorted',{from:from,to:to});
}else{
scope.$emit('my-created',{to:to,name:ui.item.text()});
ui.item.remove();
}
})
}
} );
}
}
})
在控制器中,我创建了items-array并收听事件:
$scope.items = [
{name:'Item 1'},{name:'Item 2'},{name:'Item 3'},{name:'Item 4'},];
$scope.$on('my-sorted',function(ev,val){
// rearrange $scope.items
$scope.items.splice(val.to,$scope.items.splice(val.from,1)[0]);
})
$scope.$on('my-created',val){
// create new item at position
$scope.items.splice(val.to,{name:'#'+($scope.items.length+1)+': '+val.name});
})
如您所见,当您添加或移动元素时,范围中的模型将被更新.
这些指令不是很通用 – 您可能需要进行一些调整才能使其与应用程序一起使用.