ng-draggable directive
"use strict";
ArgusApp.Common
.directive("ngDraggable", ArgusNgDraggableDirective);
ArgusNgDraggableDirective.$inject = ["$document"];
function ArgusNgDraggableDirective($document) {
return {
restrict: "E",
scope: {
draggableItem: "="
},
link: function (scope, element, attr) {
var currentElement = $(element);
var parentElement = currentElement.parent();
var elemOffsetLeft, elemOffsetTop;
element.css({
left: scope.draggableItem.xAxis + "%",
top: scope.draggableItem.yAxis + "%"
});
element.on('mousedown', function (event) {
event.preventDefault();
var elemOffset = $(element).offset();
elemOffsetLeft = event.pageX - elemOffset.left;
elemOffsetTop = event.pageY - elemOffset.top;
$document.on('mousemove', onMouseMove);
$document.on('mouseup', onMouseUp);
});
function onMouseMove(event) {
var parentOffset = parentElement.offset();
var relativeX = event.pageX - parentOffset.left - elemOffsetLeft;
var relativeY = event.pageY - parentOffset.top - elemOffsetTop;
if (relativeX < 0)
relativeX = 0;
if (relativeY < 0)
relativeY = 0;
if (relativeX > parentElement.width())
relativeX = parentElement.width();
if (relativeY > parentElement.height())
relativeY = parentElement.height();
element.css({
left: relativeX + "px",
top: relativeY + "px"
});
}
function onMouseUp() {
updateDraggableItem();
$document.off('mousemove', onMouseMove);
$document.off('mouseup', onMouseUp);
}
function updateDraggableItem() {
var left = currentElement.position().left / parentElement.width() * 100;
var top = currentElement.position().top / parentElement.height() * 100;
scope.draggableItem.xAxis = _.round(left, 2);
scope.draggableItem.yAxis = _.round(top, 2);
if (scope.draggableItem.onDragDone)
scope.draggableItem.onDragDone();
}
}
};
}