Reputation: 759
I'm coding a simple app using AngularJS (newbie here!).
This app creates a list and allows you to move elements around, into diferent boxes.
The drag and drop handling worked great when using pure Javascript on the global object. But when trying to achieve the same using directives it seems the dataTransfer object of the event 'dissapears'. Here is my directive (just for a matter of testing I replaced "ondragstart" with "click"):
FulboApp.directive('insertPlayers',function(){
return {
restrict:'E',
template:'<img class="img-thumbnail" draggable="true" src="img/horangel.jpg" id="{{play.id}}" ng-dblclick="deletePlayer(play.id)" />',
replace:true,
link: function($scope,element,attrs){
$(element).on('click',function(ev){
//returns 'undefined'
console.log(ev.dataTransfer);
//ev.dataTransfer.setData('text',ev.target.id);
});
}
}
});
I tried using 'addEventListener', 'on', 'bind' and same happens What am I missing?
Is there a better overall approach to what I'm trying to do?
Edit:
All of the angular code, therefore, all of the Javascript is placed within
(function(){
...
//Here
...
})()
Upvotes: 1
Views: 2229
Reputation: 123739
You need to use dragstart
event (not ondragstart
unless you are binding event via attribute) in order to receive appropriate event with dataTransfer
property. For example click
event is not same as dragstart
event in terms of what the event object represents. try:
element.on('dragstart', function(ev) {
//....
});
Basic Demo
angular.module('app', []).directive('insertPlayers', function() {
return {
restrict: 'E',
template: '<img class="img-thumbnail" draggable="true" src="http://placehold.it/32x32" id="asdf" ng-dblclick="deletePlayer(play.id)" />',
replace: true,
link: function($scope, tElm) {
tElm.on('dragstart', function dragstart(event) {
event.dataTransfer.setData('text/plain', event.target.id);
});
}
}
}).directive('droppable', function() {
return {
restrict: 'E',
link: function(scope, tElm) {
tElm.on('dragover', function dragover(ev) {
ev.preventDefault();
});
tElm.on('drop', function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
});
}
}
});
#div1 {
border: 1px solid #000;
height: 32px;
width: 32px;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js">
</script>
<div ng-app='app'>
<insert-players></insert-players>
<droppable id="div1"></droppable>
</div>
Upvotes: 1