Defining the Draggable Custom AngularJS Directive

Listing 29.13 defines a custom directive named richDraggable. This directive stores the initial position of the element passed in when the template is compiled and then registers a handler with the mousedown event on the element.

When the mouse is pressed, the handler adds events for mousemove and mouseup. The mousemove handler adjusts the top and left CSS attributes to move the element around the screen. The mouseup event handler unbinds the mousemove and mouseup event handlers to stop dragging.

Listing 29.13 rich_ui_app.js-richDraggable: Implementing the AngularJS custom directive to allow page elements to be moved


001 var app = angular.module('richApp', []);
. . .
108 app.directive('richDraggable', function($document, $window) {
109   return function(scope, element, attr) {
110     var startX = 0, startY = 0;
111     var x = Math.floor((Math.random()*500)+40);
112     var y = Math.floor((Math.random()*360)+40);
113     element.css({
114       position: 'absolute',
115       cursor: 'pointer',
116       top: y + 'px',
117       left: x + 'px'
118     });
119     element.on('mousedown', function(event) {
120       event.preventDefault();
121       startX = event.pageX - x;
122       startY = event.pageY - y;
123       $document.on('mousemove', mousemove);
124       $document.on('mouseup', mouseup);
125     });
126     function mousemove(event) {
127       y = event.pageY - startY;
128       x = event.pageX - startX;
129       element.css({
130         top: y + 'px',
131         left:  x + 'px'
132       });
133     }
134     function mouseup() {
135       $document.unbind('mousemove', mousemove);
136       $document.unbind('mouseup', mouseup);
137     }
138   };
139 });


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.162.204