The following code demonstrates how to make a dom element draggable in
AngularJS way:
Demo
movable.html |
repository |
view raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | <!doctype html>
<html ng-app="draggableModule">
<head>
<meta charset="utf-8">
<title>AngularJS Draggable (Movable, Drag and Drop) DOM Element Example</title>
</head>
<body>
<div draggable style="width: 200px; height: 200px; background: yellow;">Drag Me</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="ngdraggable.js"></script>
</script>
</body>
</html>
|
ngdraggable.js |
repository |
view raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 | 'use strict';
angular.module('draggableModule', []).
directive('draggable', ['$document' , function($document) {
return {
restrict: 'A',
link: function(scope, elm, attrs) {
var startX, startY, initialMouseX, initialMouseY;
elm.css({position: 'absolute'});
elm.bind('mousedown', function($event) {
startX = elm.prop('offsetLeft');
startY = elm.prop('offsetTop');
initialMouseX = $event.clientX;
initialMouseY = $event.clientY;
$document.bind('mousemove', mousemove);
$document.bind('mouseup', mouseup);
return false;
});
function mousemove($event) {
var dx = $event.clientX - initialMouseX;
var dy = $event.clientY - initialMouseY;
elm.css({
top: startY + dy + 'px',
left: startX + dx + 'px'
});
return false;
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
}
};
}]);
|
If you prefer to do this in pure JavaScript way, see reference .
If you want to know how to do this in
Dart, see reference .
References: