Search code examples
javascriptjqueryangularjsdrag-and-dropdraggable

event.dataTransfer and event.originalEvent are always null inside dragstart event handler


I'm trying to create drag and drop directives for angularJS by following this post: http://jasonturim.wordpress.com/2013/09/01/angularjs-drag-and-drop/

But I can not send any data because inside the dragstart event handler dataTransfer and the originalEvent are always null.

My drag directive looks like this:

directives.directive('draggSrc', ['$rootScope', 'UuidService', function ($rootScope, UuidService) {
    var directive = {};

    directive.restrict = 'A';

    directive.link = function (scope, el, attrs) {
        el.attr("draggable", "true");
        var id = attrs.id;
        if (!attrs.id) {
            id = UuidService.new();
            el.attr("id", id);
        }

        el.bind("dragstart", function (evt) {
            console.log(evt);
            console.log(evt.dataTransfer);
            console.log(evt.originalEvent);
            evt.dataTransfer.setData('text', id);

            $rootScope.$emit("DRAG-START");
        });

        el.bind("dragend", function (evt) {
            $rootScope.$emit("DRAG-END");
        });
    };

    return directive;
}]);

I have also called $.event.props.push('dataTransfer').


Solution

  • In order to solve my problem I have switched from using jQuery's bind to using JavaScript's addEventListener and everything worked as expected:

    directives.directive('draggSrc', ['$rootScope', 'UuidService', function ($rootScope, UuidService) {
        var directive = {};
    
        directive.restrict = 'A';
    
        directive.link = function (scope, el, attrs) {
            el.attr("draggable", "true");
            var id = attrs.id;
            if (!attrs.id) {
                id = UuidService.new();
                el.attr("id", id);
            }
    
            el.get(0).addEventListener("dragstart", function (evt) {
                evt.dataTransfer.setData('text', id);
                $rootScope.$emit("DRAG-START");
            });
    
            el.get(0).addEventListener("dragend", function (evt) {
                $rootScope.$emit("DRAG-END");
            });
        };
    
        return directive;
    }]);