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

基于AngularJS拖拽插件ngDraggable.js实现拖拽排序功能

程序员文章站 2022-03-07 09:40:49
ngdraggable.js是一款比较简单实用的angularjs拖拽插件,借助于封装好的一些自定义指令,能够快速的进行一些拖拽应用开发。首先先介绍一些基本的概念;...

ngdraggable.js是一款比较简单实用的angularjs拖拽插件,借助于封装好的一些自定义指令,能够快速的进行一些拖拽应用开发。首先先介绍一些基本的概念;

•ng-drop:是否允许放入拖拽元素

•ng-drop-success($data, $event):拖拽元素放入的回调;$data:放入元素数据;$event拖拽事件对象

•ng-drag:元素是否允许拖拽

•ng-drag-success($data, $event):$data:拖拽元素数据,$event拖拽元素事件对象

•ng-drag-data:拖拽数据

  官方链接:https://github.com/fatlinesofcode/ngdraggable

  在拖拽进行元素排序时,只需动态更改下循环数组元素顺序;具体事件绑定drop绑定在父元素,drag绑定在子元素即可,具体实现代码如下:

效果图如下:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <style>
    .drag-container {
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }
    .drag-container .drag-box {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 200px;
      height: 200px;
      margin: 20px;
      color: #fff;
      font-size: 20px;
      font-weight: bold;
    }
    .drag-container .drag-box .drag-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 150px;
      height: 150px;
    }
  </style>
  <title>ng-dragger</title>
</head>
<body ng-app="app" ng-controller="draggercontroller">
  <div class="drag-container">
    <div ng-repeat="item in dragarr" class="drag-box" ng-drop="true" ng-drop-success="ondropcomplete($index, $data, $event)">
      <div class="drag-item" ng-drag="true" ng-drag-data="{{item}}" ng-style="{background: item.color}">{{item.text}}</div>
    </div>
  </div>
  <script src="https://cdn.bootcss.com/angular.js/1.3.1/angular.js"></script>
  <script src="https://cdn.bootcss.com/ngdraggable/0.1.11/ngdraggable.js"></script>
  <script>
    var myapp = angular.module('app', ['ngdraggable']);
    myapp.controller('draggercontroller', function($scope) {
      $scope.dragarr = [{
        text: '方块1',
        color: 'green',
        key: 'arr1'
      }, {
        text: '方块2',
        color: 'blue',
        key: 'arr1'
      }, {
        text: '方块3',
        color: '#888',
        key: 'arr1'
      }, {
        text: '方块4',
        color: '#888',
        key: 'arr2'
      }, {
        text: '方块5',
        color: '#888',
        key: 'arr2'
      }, {
        text: '方块6',
        color: '#888',
        key: 'arr2'
      }];
      $scope.ondropcomplete = function(index, obj, $event) {
        var otherobj = $scope.dragarr[index];
        var otherindex = $scope.dragarr.findindex(vv => object.is(vv.text, obj.text));
        if (otherobj.key !== obj.key) return;
        $scope.dragarr[index] = obj;
        $scope.dragarr[otherindex] = otherobj;
      }
    })
  </script>
</body>
</html>

基于AngularJS拖拽插件ngDraggable.js实现拖拽排序功能

总结

以上所述是小编给大家介绍的基于angularjs拖拽插件ngdraggable.js实现拖拽排序功能,希望对大家有所帮助