2014-05-08

[AngularJS] 製作 Mouse Drag Event directive

Html
<div ng-style="{'top': itemTop, 'left': itemLeft}"
    my-mousedrag="itemTop = itemTop - $deltaY; itemLeft = itemLeft - $deltaX"
></div>

JavaScript
app.directive('myMousedrag', function() {
    return function(scope, element, attrs) {
        var prevEvent;
        element.mousedown(function(event){
            prevEvent = event;

        }).mouseup(function(event){
            prevEvent = null;

        }).mousemove(function(event){
            if(!prevEvent){ return; }

            /*將 element 拖移事件傳遞到 scope 上*/
            scope.$eval(attrs['myMousedrag'], {
                $event: event,
                $deltaX: event.clientX - prevEvent.clientX,
                $deltaY: event.clientY - prevEvent.clientY
            });

            /*通知 scope 有異動發生*/
            scope.$digest();

            prevEvent = event;
        });

        /*在 destroy 時清除事件註冊*/
        scope.$on('$destroy', function(){
            element.off('mousedown mouseup mousemove');
        });
    };
});

0 回應: