欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

angularjs结合html5实现拖拽功能

程序员文章站 2022-05-25 23:11:52
先来 看看具体效果: 实现方法: 1.下载并引入 angularjs 2.html代码:

先来 看看具体效果:

angularjs结合html5实现拖拽功能

实现方法:

1.下载并引入 angularjs

2.html代码:

<!doctype html>
<html lang="en" ng-app="test">
<head>
  <meta charset="utf-8">
  <title>html5 拖拽行为和angularjs的结合</title>
  <meta charset="utf-8"/>
  <script type="text/javascript" src="js/angular.js"></script>
  <style>
    .to-drag, .drag-stop {
      display: inline-block;
    }
  </style>
</head>
<body ng-controller="main">
<div class="to-drag">
  <ul>
    <li ng-repeat="item in list.data" ng-include="'./lefttree.html'"></li>
  </ul>
</div>
<div class="drag-stop">
  <ul>
    <li ng-repeat="item in rightlist.data" ng-include="'./righttree.html'"></li>
  </ul>
</div>
</body>
</html>

3.js

<script type="text/javascript">
  let mod = angular.module("test", []);
  mod.controller("main", ['$scope', function ($scope) {
    $scope.list = {
      data: [{
        id: 1,
        name: '22',
        child: [{
          id: '1-1',
          name: '1-1_name-左'
        }, {
          id: '1-2',
          name: '1-2_name-左'
        }]
      }],
      dragstart: function (item) {
        $scope.clientinfo = item;
      }
    }
    $scope.rightlist = {
      data: [{
        id: 1,
        name: '停止拖动',
        child: [{
          id: '1-1',
          name: '1-1_name-右'
        }, {
          id: '1-2',
          name: '1-2_name-右'
        }]
      }],
      drop: function (event, item) {
        event.preventdefault();
        console.log("被拖动的元素:->", $scope.clientinfo);
        console.log("当前节点:->", item);
        //调用后端添加接口,实现真实的添加。
      },
      dragover: function (event) {
        event.preventdefault();
      }
    }
  }]);
  var convertfirstuppercase = function (str) {
    return str.replace(/(\w)/, function (s) {
      return s.touppercase();
    });
  };
  rubydrageventdirectives = {};
  angular.foreach("dragstart drag dragenter dragover drop dragleave dragend".split(' '), function (eventname) {
    var rubyeventname = 'ruby' + convertfirstuppercase(eventname);
    rubydrageventdirectives[rubyeventname] = ['$parse', function ($parse) {
      //$parse 语句解析器
      return {
        restrict: 'a',
        compile: function (ele, attr) {
          var fn = $parse(attr[rubyeventname]);
          return function rubyeventhandler(scope, ele) {
            ele[0].addeventlistener(eventname, function (event) {
              if (eventname == 'dragover' || eventname == 'drop') {
                event.preventdefault();
              }
              var callback = function () {
                fn(scope, {event: event});
              };
              callback();
            });
          }
        }
      }
    }]
  });
  mod.directive(rubydrageventdirectives);
</script>

希望可以对大家有所帮助哦。好久都没写博客啦,嘻嘻最近变懒了,而且特别懒,哈哈哈哈,天热啦,大家多喝水哦,注意防暑。