Tutorial 12.13 Creating a Directive that Adds Event Listeners

******************************************INDEX.HTML*****************************************************
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-directive-drag-production</title>
 

  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="script.js"></script>
 

 
</head>
<body ng-app="dragModule">
  <span my-draggable>Drag Me</span>
</body>
</html>

******************************************INDEX.HTML*****************************************************
********************************************script.js***************************************************
(function(angular) {
  'use strict';
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: 'relative',
         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;
          element.css({
            top: y + 'px',
            left:  x + 'px'
          });
        }

        function mouseup() {
          $document.off('mousemove', mousemove);
          $document.off('mouseup', mouseup);
        }
      }
    };
  }]);
})(window.angular);

********************************************script.js***************************************************

Comments

Popular posts from this blog

Tutorial 12.12 Creating a Directive that Wraps Other Elements 3

Tutorial 12.14 Creating Directives that Communicate