Search code examples
angularjsdraggabledragchildrendirective

How to get on('mousedown', ....) from the child element in angularjs


I got this simple drag example from angularjs docs. here is a

plunk fork

However, I am trying to get to the child node's actions so it will drag only when clicked on the child element. I have tried :

var elementDrag=element[0].getElementsByClassName('dragThis');
elementDrag.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); 
});

Any ideas on how to approach this without using jQuery?


Solution

  • Here is a quick and dirty implementation to get you started with: http://plnkr.co/edit/1hBmpg51xqzxi0EP4WBg

    Try it out and let me know if you still have questions. The controller code needs some cleaning ;-).

    The implementation is based on two directives that communicate with each other. The outer directive (draggable-content) exposes an API allowing the inner directive (draggable-control) to perform de drag.

    .directive('draggableControl', function($document) {
      return {
        require: '^draggableContent',
        // The 4th arg of the link fn, ctrl, is the controller of the outer directive draggableContent
        link: function(scope, element, attr, ctrl) {
            // more code
            }
        };
    })
    

    The markup is straightforward:

    <body ng-app="drag">
        <div draggable-content>
        <div draggable-control class="dragThis" style='border: 1px solid yellow; background:white;'>Drag here only</div>
        DO NOT drag here<br><br><br>or here</div>
    </body>