亲宝软件园·资讯

展开

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

Gerryli 人气:0

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实现拖拽排序功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

加载全部内容

相关教程
猜你喜欢
用户评论