Skip to content

Instantly share code, notes, and snippets.

@yngvebn
Created May 11, 2016 12:27
Show Gist options
  • Save yngvebn/140c6c6d590f59841c0d91c798367d1c to your computer and use it in GitHub Desktop.
Save yngvebn/140c6c6d590f59841c0d91c798367d1c to your computer and use it in GitHub Desktop.
angular
.module('app.common', [])
.directive('bazeMovable', bazeMovable);
bazeMovable.$inject = ['$document'];
/* @ngInject */
function bazeMovable($document) {
var directive = {
bindToController: true,
controller: bazeMovableController,
controllerAs: 'vm',
link: link,
restrict: 'A',
scope:{
posX:'=?',
posY:'=?'
}
};
return directive;
function link(scope, element, attrs) {
var startX, startY, initialMouseX, initialMouseY;
element.css({position: 'absolute'});
element.bind('mousedown', function($event) {
startX = element.prop('offsetLeft');
startY = element.prop('offsetTop');
initialMouseX = $event.clientX;
initialMouseY = $event.clientY;
$document.bind('mousemove', mousemove);
$document.bind('mouseup', mouseup);
return true;
});
function mousemove($event) {
var dx = $event.clientX - initialMouseX;
var dy = $event.clientY - initialMouseY;
element.css({
top: startY + dy + 'px',
left: startX + dx + 'px'
});
scope.vm.posY=startY + dy;
scope.vm.posX=startX + dx;
scope.$evalAsync();
return false;
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
scope.$watch(function(){ return scope.vm.posY; },onMoveVert);
scope.$watch(function(){ return scope.vm.posX; },onMoveHor)
function onMoveHor(newValue, oldValue){
if(oldValue != newValue){
element.css({
left: newValue + 'px'
});
}
}
function onMoveVert(newValue, oldValue){
if(oldValue != newValue){
element.css({
top: newValue + 'px',
});
}
}
}
}
bazeMovableController.$inject = [];
/* @ngInject */
function bazeMovableController() {
var vm = this;
vm.posX;
vm.posY;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment