I want to restrict basically the following implementation of an angular.js drag directive into the boundaries of a parent element. How do I do that?
Here is a jsbin that visualizes my issue: http://jsbin.com/maxife/3/edit?html,css,js,output
I want to restrict basically the following implementation of an angular.js drag directive into the boundaries of a parent element. How do I do that?
Here is a jsbin that visualizes my issue: http://jsbin.com/maxife/3/edit?html,css,js,output
You must modify the drag directive in order to achieve this,
Since event.pageX and event.pageY properties return the position of the mouse pointer relative to the left edge of the whole document, you need to:
<span my-draggable>Drag Me</span>
How you get it into the directive? Use this: Get element parent height inside directive in AnguarJS
Again you will have to use the attributes of height and width from the parent element, but you will not have to touch the position or use offsets, just add before element.css({..}):
if(x>27){
x=27;
}
else if(x<0){
x=0;
}
if(y>77){
y=77;
}
else if(y<0){
y=0;
}
I have done it manually, so you can have an example before using the parent attributes. You will have to take span width+height in consideration if you don't want some of the span element to get outside the div of course.
The full module:
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'absolute',
border: '1px solid red',
backgroundColor: 'lightgrey',
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(x>27){
x=27;
}
else if(x<0){
x=0;
}
if(y>77){
y=77;
}
else if(y<0){
y=0;
}
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
}
};
}]);
In the JSbin: JSbin link