SoFunction
Updated on 2025-04-05

Example of using angular to help you implement drag and drop

There are many ways to write drag and drop, let’s take a look at the angular version of drag and drop here.

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
      #box{
        width: 100px;
        height: 100px;
        background: black;
        /*Be sure to set absolute positioning for the current element*/
        position: absolute;
        left: 0;
        top: 0;
      }
    </style>
  </head>
  <body>
    <div  my-drag></div>
  </body>
    <script src="jquery-3.1." type="text/javascript" charset="utf-8"></script>
    <script src="../js/" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
// Customize a module      var app = ("myApp",[]);
// Custom directives You must use camel nomenclature when customizing directives      ('myDrag',function(){
// Return a function        return{
          link : function(scope,element,attr){
// data that scope can receive// element Current element// attr attribute 
// The three major events dragged and dropped mousedown, mousemove, mouseup. Use the method of binding the event to bind the event            ('mousedown',function(ev){
// Get the current object through event              var This = $(this);
// Get the distance from the border on the current element              var disX =  - $(this).offset().left;
// Get the distance from the left border of the element// Because what remains unchanged during dragging is the distance between the mouse and the element border through constant and known variables              var disY =  - $(this).offset().top;
              $(document).on('mousemove',function(ev){
// Set the changed value to the current element through style                ({
                  left: - disX,
                  top: - disY,
                });
              });
              $(document).on('mouseup',function(){
// Close all events when the mouse is released                $(document).off();
              })
            })
          },
          restrict:'A', //ECMA E element C class name M annotation A attribute        };
      });
    </script>
</html>

The above example of using angular to help you achieve drag and drop is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.