Created
April 20, 2015 12:23
-
-
Save aurbano/d1bd03c3b7ba5f81beab to your computer and use it in GitHub Desktop.
Angular Draggable directive, with support for dragging another element, and container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('aurbano.draggable', []) | |
.directive('draggable', ['$document', function($document) { | |
return { | |
scope: { | |
config: '=draggable' | |
}, | |
link: function(scope, element, attr) { | |
var dragElement = element; | |
if(scope.config.target){ | |
if(scope.config.target === 'parent'){ | |
dragElement = element.parent(); | |
}else{ | |
dragElement = $(scope.config.target); | |
} | |
} | |
var startX = 0, | |
startY = 0, | |
x = element.offset().left - element.outerWidth(), | |
y = element.offset().top - element.outerHeight(); | |
console.log(x, y); | |
element.css({ | |
position: 'relative', | |
cursor: 'pointer' | |
}); | |
element.on('mousedown', function(event) { | |
// Prevent default dragging of selected content | |
event.preventDefault(); | |
startX = event.pageX - x; | |
startY = event.pageY - y; | |
$document.on('mousemove', mousemove); | |
$document.on('mouseup', mouseup); | |
}); | |
function mousemove(event) { | |
y = event.pageY - startY; | |
x = event.pageX - startX; | |
if(scope.config.container){ | |
var containerEl = $(scope.config.container); | |
var limits = { | |
minX : containerEl.offset().left, | |
maxX : containerEl.offset().left + containerEl.outerWidth() - dragElement.outerWidth(), | |
minY : containerEl.offset().top, | |
maxY : containerEl.offset().top + containerEl.outerHeight() - dragElement.outerHeight() | |
}; | |
x = Math.max(limits.minX, Math.min(limits.maxX, x)); | |
y = Math.max(limits.minY, Math.min(limits.maxY, y)); | |
} | |
dragElement.css({ | |
top: y + 'px', | |
left: x + 'px' | |
}); | |
} | |
function mouseup() { | |
$document.off('mousemove', mousemove); | |
$document.off('mouseup', mouseup); | |
} | |
} | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment