I'm implementing a image draggable directive. My code is at http://plnkr.co/edit/MXnOu6HM1XmMEzot7dn3 Basically its primarily made up of a base movable directive
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);
}
}
}
});
And an image directive
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;
}
};
});
However, as seen in plunkr, when i first click on the image and try to drag, it goes through several passes of the mousemove
event, and then freezes, not moving anymore. Subsequently releasing my mouse moves the image, strangely. Any idea what i'm doing wrong here??
There is a working example of draggable directive in Angular.js documentation http://docs.angularjs.org/guide/directive
This is a fork of your Plunker within that directive: http://plnkr.co/edit/RmzmgubOfF1VdU7HaAtp?p=preview
I have to answer my own question here. I should use event.preventDefault
in mousemove
function to prevent the browser from using the default image drag and drop functionality here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With