AngulatrJs中的draggable和droppable怎么封装成指令
巴扎黑2017-04-10 16:23:47
我恰好封装过,代码如下。使用方法同ng-click,其实这就是用ng-click的代码改的。你可以根据自己的需要修改。
.directive('myDragstart', function ($parse) {
return {
restrict: 'A', link(scope, element, attrs) {
var fn = $parse(attrs.myDragstart);
element[0].draggable = 'true';
element[0].ondragstart = function (e) {
e.dataTransfer.effectAllowed = 'move';
return scope.$apply(function () {
return fn(scope, {$event: e});
});
};
}
};
}).directive('myDrop', function ($parse) {
return {
restrict: 'A', link(scope, element, attrs) {
var fn = $parse(attrs.myDrop);
element[0].ondrop = function (e) {
e.preventDefault()
return scope.$apply(function () {
return fn(scope, {$event: e});
});
};
element[0].ondragover = function(e) {
e.preventDefault();
return true;
};
}
};
});
黄舟2017-04-10 16:23:47
拿去吧,刚学ng时候写的,给你参考下
var dragSrcEl;
directives.directive('ngDragstart',function($rootScope){
return{
restrict: 'A',
link: function(scope, element) {
element.bind('dragstart', function(e){
$rootScope.dragging = true;
if( e.target.parentNode.className.search('aaa') !== -1){
e.target.parentNode.style.opacity = '0.4';
dragSrcEl = e.target.parentNode;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setDragImage(e.target.parentNode,80,5);
e.dataTransfer.setData('text/html', e.target.parentNode.innerHTML);
}else if(e.target.className.search('jstree-anchor') != -1){
dragSrcEl = e.target;
e.dataTransfer.effectAllowed = 'move';
if($rootScope.hover_node){
var id = $rootScope.hover_node['original']['metadata']['id'];
e.dataTransfer.setData('text', id.toString());
}
}
else{
e.preventDefault();
}
});
}
};
});
directives.directive('ngDragover',function(){
return{
restrict: 'A',
link: function(scope, element) {
element.bind('dragover', function(e) {
if (e.preventDefault && e.target.className.search('aaa') !== -1) {
e.preventDefault();
}
else if (e.preventDefault && e.target.className.search('jstree-anchor') !== -1) {
e.preventDefault();
}
e.dataTransfer.dropEffect = 'move';
return false;
});
}
};
});
directives.directive('ngDragend',function(){
return{
restrict: 'A',
link: function(scope, element) {
element.bind('dragend', function(e) {
e.target.style.opacity='1.0';
e.target.parentNode.style.opacity='1.0';
});
}
};
});
directives.directive('ngDrop',function($rootScope){
return{
restrict: 'A',
link: function(scope, element) {
element.bind('drop', function(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (e.currentTarget.className.search('aaa') !== -1 && dragSrcEl.className === e.currentTarget.className) {
var aId = $(e.currentTarget).find('.paramId').text();
var bId = $(dragSrcEl).find('.paramId').text();
$rootScope.$broadcast('swapPod',[aId,bId]);
}else if(dragSrcEl.className.search('jstree-anchor') !== -1 &&(e.currentTarget.className === "podList" || e.currentTarget.className.search('aaa') !== -1)){
var id = e.dataTransfer.getData('text');
$rootScope.$broadcast('addPod',id);
}
$rootScope.dragging = false;
return false;
});
}
};
});