Created
November 24, 2014 14:29
-
-
Save EpokK/50b01000b2e914d9f648 to your computer and use it in GitHub Desktop.
dnd js natif with angularJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var app = angular.module('dragDrop', []); | |
app.directive('draggable', function() { | |
return function(scope, element) { | |
// this gives us the native JS object | |
var el = element[0]; | |
el.draggable = true; | |
el.addEventListener( | |
'dragstart', | |
function(e) { | |
e.dataTransfer.effectAllowed = 'move'; | |
e.dataTransfer.setData('Text', this.id); | |
this.classList.add('drag'); | |
return false; | |
}, | |
false | |
); | |
el.addEventListener( | |
'dragend', | |
function(e) { | |
this.classList.remove('drag'); | |
return false; | |
}, | |
false | |
); | |
} | |
}); | |
app.directive('droppable', function() { | |
return { | |
scope: { | |
drop: '&', | |
bin: '=' | |
}, | |
link: function(scope, element) { | |
// again we need the native object | |
var el = element[0]; | |
el.addEventListener( | |
'dragover', | |
function(e) { | |
e.dataTransfer.dropEffect = 'move'; | |
// allows us to drop | |
if (e.preventDefault) e.preventDefault(); | |
this.classList.add('over'); | |
return false; | |
}, | |
false | |
); | |
el.addEventListener( | |
'dragenter', | |
function(e) { | |
this.classList.add('over'); | |
return false; | |
}, | |
false | |
); | |
el.addEventListener( | |
'dragleave', | |
function(e) { | |
this.classList.remove('over'); | |
return false; | |
}, | |
false | |
); | |
el.addEventListener( | |
'drop', | |
function(e) { | |
// Stops some browsers from redirecting. | |
if (e.stopPropagation) e.stopPropagation(); | |
this.classList.remove('over'); | |
var binId = this.id; | |
var item = document.getElementById(e.dataTransfer.getData('Text')); | |
this.appendChild(item); | |
// call the passed drop function | |
scope.$apply(function(scope) { | |
var fn = scope.drop(); | |
if ('undefined' !== typeof fn) { | |
fn(item.id, binId); | |
} | |
}); | |
return false; | |
}, | |
false | |
); | |
} | |
} | |
}); | |
app.controller('DragDropCtrl', function($scope) { | |
$scope.handleDrop = function(item, bin) { | |
alert('Item ' + item + ' has been dropped into ' + bin); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment