event.dataTransfer和event.originalEvent在dragstart事件处理程序中始终为null

时间:2014-07-10 17:45:12

标签: javascript jquery angularjs drag-and-drop draggable

我尝试按照以下帖子为angularJS创建拖放指令:http://jasonturim.wordpress.com/2013/09/01/angularjs-drag-and-drop/

但我无法发送任何数据,因为在dragstart事件处理程序dataTransfer中,originalEvent始终为null。

我的拖拽指令如下所示:

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;
}]);

我也打电话给$.event.props.push('dataTransfer')

2 个答案:

答案 0 :(得分:4)

为了解决我的问题,我已经从使用jQuery' bind转为使用JavaScript addEventListener,一切都按预期工作:

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;
}]);

答案 1 :(得分:2)

使用其他修补程序遇到同样的问题:如果您的放置处理程序中有alert()confirm()对话框,则会清除event.dataTransfer