angularjs draggable指令

时间:2013-12-05 07:22:31

标签: javascript angularjs angularjs-directive

我正在实现一个图像可拖动指令。我的代码位于http://plnkr.co/edit/MXnOu6HM1XmMEzot7dn3基本上它主要由基本可移动指令

组成
appModule.directive('movable', function ($document) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function postLink(scope, element, attrs) {
                var startX = 0,
                    startY = 0,
                    x = 0,
                    y = 0;

                element.css({
                    position: 'absolute'
                });

                function bindElementMove() {
                    element.bind('mousedown', function (event) {
                        // Prevent default dragging of selected content
                        console.log("binding element to move.");
                        startX = event.screenX - x;
                        startY = event.screenY - y;
                        $document.bind('mousemove', moveDiv);
                        $document.bind('mouseup', mouseup);
                    });
                }

                bindElementMove();

                function moveDiv(event) {
                    console.log('im moving');
                    y = event.screenY - startY;
                    x = event.screenX - startX;
                    element.css({
                        top: y + 'px',
                        left: x + 'px'
                    });
                    scope.$apply(function () {
                        scope.tb.x = element.css("top");
                        scope.tb.y = element.css("left");
                    });
                }

                function mouseup() {
                    console.log("mouse up fired - unbind moveDiv and mouseUp");
                    $document.unbind('mousemove', moveDiv);
                    $document.unbind('mouseup', mouseup);
                }
            }
        }
    });

图像指令

appModule.directive("imgelement", function ($document) {
    return {
        restrict: 'E',
        template: '<div movable resizable constrain deletable rotatable ng-style="{top:tb.x, left:tb.y, height:tb.height, width:tb.width}"><img ng-src="{{tb.blob_url}}"  ng-style="{height:tb.height, width:tb.width}"/></div>',
        require: 'ngModel',
        replace: true,
        link: function (scope, element, attrs) {
            hello = scope;
        }
    };
});

然而,正如在plunkr中所见,当我第一次点击图像并尝试拖动时,它会经历mousemove事件的几次传递,然后冻结,不再移动。随后释放我的鼠标移动图像,奇怪的是。知道我在这里做错了什么?

2 个答案:

答案 0 :(得分:10)

Angular.js文档http://docs.angularjs.org/guide/directive

中有一个draggable指令的工作示例

这是你的指令中的一个分叉:http://plnkr.co/edit/RmzmgubOfF1VdU7HaAtp?p=preview

答案 1 :(得分:5)

我必须在这里回答我自己的问题。我应该在event.preventDefault函数中使用mousemove来阻止浏览器在此处使用默认的图像拖放功能。