如何在angularjs中创建简单的拖放

时间:2022-08-22 20:25:29

I want to know how to do drag and drop by using AngularJs.

我想知道如何使用AngularJs来拖放。

This is what I have so far:

这就是我目前所拥有的:

<span><input type="checkbox" ng-model="master"><span>SelectAll</span></span>
<div ng-repeat="todo in todos">

    <div ng-hide="enableEditor">
        <a href="#">Drag</a>
        <input id="checkSlave" type="checkbox" ng-checked="master" ng-model="todo.done">

        <span ng-if="checked" ng-show="removed" ng-bind="todo.task_name" class="removed"></span>
        <span ng-bind="todo.task_name"></span>
        <span ng-bind="todo.state"></span>
        <a href="#" ng-click="editTask(todo.task_id,todo.task_name,editMode=!editMode)">Edit</a> 

       </div>
       </div>

    <div ng-show="enableEditor">
     <input type="text" ng-show="editMode" ng-model="todo.task_name"  ng-change="update(todo.task_id,todo.task_name)">
     <a href="#" ng-click="saveTask(todo.task_id,todo.task_name,editMode=!editMode)">Save</a>
     <a href="#" ng-click="cancelTask(todo.task_id,todo.task_name,editMode=!editMode)">Cancel</a>
    </div>
</div>

http://plnkr.co/edit/llTH9nRic3O2S7XMIi6y?p=preview..

http://plnkr.co/edit/llTH9nRic3O2S7XMIi6y?p=preview.。

7 个解决方案

#1


71  

I just posted this to my brand spanking new blog: http://jasonturim.wordpress.com/2013/09/01/angularjs-drag-and-drop/

我刚把这篇文章发布到我的新博客:http://jasonturim.wordpress.com/2013/09/01/angularjs-drag- drop/上

Code here: https://github.com/logicbomb/lvlDragDrop

代码:https://github.com/logicbomb/lvlDragDrop

Demo here: http://logicbomb.github.io/ng-directives/drag-drop.html

演示:http://logicbomb.github.io/ng-directives/drag-drop.html

Here are the directives these rely on a UUID service which I've included below:

以下是这些依赖于UUID服务的指令,我将它们包括在下面:

var module = angular.module("lvl.directives.dragdrop", ['lvl.services']);

module.directive('lvlDraggable', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            link: function(scope, el, attrs, controller) {
                console.log("linking draggable element");

                angular.element(el).attr("draggable", "true");
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragstart", function(e) {
                    e.dataTransfer.setData('text', id);

                    $rootScope.$emit("LVL-DRAG-START");
                });

                el.bind("dragend", function(e) {
                    $rootScope.$emit("LVL-DRAG-END");
                });
            }
        }
    }]);

module.directive('lvlDropTarget', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            scope: {
                onDrop: '&'
            },
            link: function(scope, el, attrs, controller) {
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragover", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                  return false;
                });

                el.bind("dragenter", function(e) {
                  // this / e.target is the current hover target.
                  angular.element(e.target).addClass('lvl-over');
                });

                el.bind("dragleave", function(e) {
                  angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
                });

                el.bind("drop", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                  }
                    var data = e.dataTransfer.getData("text");
                    var dest = document.getElementById(id);
                    var src = document.getElementById(data);

                    scope.onDrop({dragEl: src, dropEl: dest});
                });

                $rootScope.$on("LVL-DRAG-START", function() {
                    var el = document.getElementById(id);
                    angular.element(el).addClass("lvl-target");
                });

                $rootScope.$on("LVL-DRAG-END", function() {
                    var el = document.getElementById(id);
                    angular.element(el).removeClass("lvl-target");
                    angular.element(el).removeClass("lvl-over");
                });
            }
        }
    }]);

UUID service

UUID服务

angular
.module('lvl.services',[])
.factory('uuid', function() {
    var svc = {
        new: function() {
            function _p8(s) {
                var p = (Math.random().toString(16)+"000000000").substr(2,8);
                return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
            }
            return _p8() + _p8(true) + _p8(true) + _p8();
        },

        empty: function() {
          return '00000000-0000-0000-0000-000000000000';
        }
    };

    return svc;
});

#2


25  

Angular doesn't provide snazzy UI elements like drag and drop. That's not really Angular's purpose. However, there are a few well known directives that provide drag and drop. Here are two that I've used.

angle不提供时髦的UI元素,比如拖放。这并不是角的目的。但是,有一些众所周知的指令提供拖放。这里有两个我用过的。

https://github.com/angular-ui/ui-sortable

https://github.com/angular-ui/ui-sortable

https://github.com/codef0rmer/angular-dragdrop

https://github.com/codef0rmer/angular-dragdrop

#3


12  

I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).

我在聚会上有点晚了,但我有自己的指示,看起来会适合你的情况(你可以自己调整)。它是对ng-repeat指令的修改,该指令是专门为通过DnD重新排序列表而构建的。我构建它是因为我不喜欢JQuery UI(比其他任何东西都更喜欢更少的库),我也希望我的作品也能在触摸屏上工作。

Code is here: http://codepen.io/SimeonC/pen/AJIyC

代码是:http://codepen.io/SimeonC/pen/AJIyC

Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/

博客文章如下:http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop- drop- reorderin ngrepeat/

#4


8  

http://blog.parkji.co.uk/2013/08/11/native-drag-and-drop-in-angularjs.html This is simple method for creating native draggable angularJS elements

http://blog.parkji.co.uk/2013/08/11/native-drag-and-drop-in-angularjs。这是创建本地可拖动的angularJS元素的简单方法

#5


5  

Modified from the angular-drag-and-drop-lists examples page

从angular拖放列表示例页面修改

Markup

<div class="row">
    <div ng-repeat="(listName, list) in models.lists" class="col-md-6">
        <ul dnd-list="list">
            <li ng-repeat="item in list" 
                dnd-draggable="item" 
                dnd-moved="list.splice($index, 1)" 
                dnd-effect-allowed="move" 
                dnd-selected="models.selected = item" 
                ng-class="{'selected': models.selected === item}" 
                draggable="true">{{item.label}}</li>
        </ul>
    </div>
</div>

Angular

var app = angular.module('angular-starter', [
    'ui.router',
    'dndLists'
]);

app.controller('MainCtrl', function($scope){

    $scope.models = {
        selected: null,
        lists: {"A": [], "B": []}
    };

    // Generate initial model
    for (var i = 1; i <= 3; ++i) {
        $scope.models.lists.A.push({label: "Item A" + i});
        $scope.models.lists.B.push({label: "Item B" + i});
    }

    // Model to JSON for demo purpose
    $scope.$watch('models', function(model) {
        $scope.modelAsJson = angular.toJson(model, true);
    }, true);
});

Library can be installed via bower or npm: angular-drag-and-drop-lists

库可以通过bower或npm安装:angular-drag- drop-list

#6


4  

adapt-strap has very light weight module for this. here is the fiddle. Here are some attributes that are supported. There are more.

适配器带为此有非常轻的重量模块。这是小提琴。下面是一些支持的属性。有更多的。

ad-drag="true"
ad-drag-data="car"
ad-drag-begin="onDragStart($data, $dragElement, $event);"
ad-drag-end="onDataEnd($data, $dragElement, $event);"

#7


0  

small scripts for drag and drop by angular

小脚本的拖放角

(function(angular) {
  'use strict';
angular.module('drag', []).
  directive('draggable', function($document) {
    return function(scope, element, attr) {
      var startX = 0, startY = 0, x = 0, y = 0;
      element.css({
       position: 'relative',
       border: '1px solid red',
       backgroundColor: 'lightgrey',
       cursor: 'pointer',
       display: 'block',
       width: '65px'
      });
      element.on('mousedown', function(event) {
        // Prevent default dragging of selected content
        event.preventDefault();
        startX = event.screenX - x;
        startY = event.screenY - y;
        $document.on('mousemove', mousemove);
        $document.on('mouseup', mouseup);
      });

      function mousemove(event) {
        y = event.screenY - startY;
        x = event.screenX - startX;
        element.css({
          top: y + 'px',
          left:  x + 'px'
        });
      }

      function mouseup() {
        $document.off('mousemove', mousemove);
        $document.off('mouseup', mouseup);
      }
    };
  });
})(window.angular);

source link

来源链接

#1


71  

I just posted this to my brand spanking new blog: http://jasonturim.wordpress.com/2013/09/01/angularjs-drag-and-drop/

我刚把这篇文章发布到我的新博客:http://jasonturim.wordpress.com/2013/09/01/angularjs-drag- drop/上

Code here: https://github.com/logicbomb/lvlDragDrop

代码:https://github.com/logicbomb/lvlDragDrop

Demo here: http://logicbomb.github.io/ng-directives/drag-drop.html

演示:http://logicbomb.github.io/ng-directives/drag-drop.html

Here are the directives these rely on a UUID service which I've included below:

以下是这些依赖于UUID服务的指令,我将它们包括在下面:

var module = angular.module("lvl.directives.dragdrop", ['lvl.services']);

module.directive('lvlDraggable', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            link: function(scope, el, attrs, controller) {
                console.log("linking draggable element");

                angular.element(el).attr("draggable", "true");
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragstart", function(e) {
                    e.dataTransfer.setData('text', id);

                    $rootScope.$emit("LVL-DRAG-START");
                });

                el.bind("dragend", function(e) {
                    $rootScope.$emit("LVL-DRAG-END");
                });
            }
        }
    }]);

module.directive('lvlDropTarget', ['$rootScope', 'uuid', function($rootScope, uuid) {
        return {
            restrict: 'A',
            scope: {
                onDrop: '&'
            },
            link: function(scope, el, attrs, controller) {
                var id = attrs.id;
                if (!attrs.id) {
                    id = uuid.new()
                    angular.element(el).attr("id", id);
                }

                el.bind("dragover", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
                  return false;
                });

                el.bind("dragenter", function(e) {
                  // this / e.target is the current hover target.
                  angular.element(e.target).addClass('lvl-over');
                });

                el.bind("dragleave", function(e) {
                  angular.element(e.target).removeClass('lvl-over');  // this / e.target is previous target element.
                });

                el.bind("drop", function(e) {
                  if (e.preventDefault) {
                    e.preventDefault(); // Necessary. Allows us to drop.
                  }

                  if (e.stopPropagation) {
                    e.stopPropagation(); // Necessary. Allows us to drop.
                  }
                    var data = e.dataTransfer.getData("text");
                    var dest = document.getElementById(id);
                    var src = document.getElementById(data);

                    scope.onDrop({dragEl: src, dropEl: dest});
                });

                $rootScope.$on("LVL-DRAG-START", function() {
                    var el = document.getElementById(id);
                    angular.element(el).addClass("lvl-target");
                });

                $rootScope.$on("LVL-DRAG-END", function() {
                    var el = document.getElementById(id);
                    angular.element(el).removeClass("lvl-target");
                    angular.element(el).removeClass("lvl-over");
                });
            }
        }
    }]);

UUID service

UUID服务

angular
.module('lvl.services',[])
.factory('uuid', function() {
    var svc = {
        new: function() {
            function _p8(s) {
                var p = (Math.random().toString(16)+"000000000").substr(2,8);
                return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
            }
            return _p8() + _p8(true) + _p8(true) + _p8();
        },

        empty: function() {
          return '00000000-0000-0000-0000-000000000000';
        }
    };

    return svc;
});

#2


25  

Angular doesn't provide snazzy UI elements like drag and drop. That's not really Angular's purpose. However, there are a few well known directives that provide drag and drop. Here are two that I've used.

angle不提供时髦的UI元素,比如拖放。这并不是角的目的。但是,有一些众所周知的指令提供拖放。这里有两个我用过的。

https://github.com/angular-ui/ui-sortable

https://github.com/angular-ui/ui-sortable

https://github.com/codef0rmer/angular-dragdrop

https://github.com/codef0rmer/angular-dragdrop

#3


12  

I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).

我在聚会上有点晚了,但我有自己的指示,看起来会适合你的情况(你可以自己调整)。它是对ng-repeat指令的修改,该指令是专门为通过DnD重新排序列表而构建的。我构建它是因为我不喜欢JQuery UI(比其他任何东西都更喜欢更少的库),我也希望我的作品也能在触摸屏上工作。

Code is here: http://codepen.io/SimeonC/pen/AJIyC

代码是:http://codepen.io/SimeonC/pen/AJIyC

Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/

博客文章如下:http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop- drop- reorderin ngrepeat/

#4


8  

http://blog.parkji.co.uk/2013/08/11/native-drag-and-drop-in-angularjs.html This is simple method for creating native draggable angularJS elements

http://blog.parkji.co.uk/2013/08/11/native-drag-and-drop-in-angularjs。这是创建本地可拖动的angularJS元素的简单方法

#5


5  

Modified from the angular-drag-and-drop-lists examples page

从angular拖放列表示例页面修改

Markup

<div class="row">
    <div ng-repeat="(listName, list) in models.lists" class="col-md-6">
        <ul dnd-list="list">
            <li ng-repeat="item in list" 
                dnd-draggable="item" 
                dnd-moved="list.splice($index, 1)" 
                dnd-effect-allowed="move" 
                dnd-selected="models.selected = item" 
                ng-class="{'selected': models.selected === item}" 
                draggable="true">{{item.label}}</li>
        </ul>
    </div>
</div>

Angular

var app = angular.module('angular-starter', [
    'ui.router',
    'dndLists'
]);

app.controller('MainCtrl', function($scope){

    $scope.models = {
        selected: null,
        lists: {"A": [], "B": []}
    };

    // Generate initial model
    for (var i = 1; i <= 3; ++i) {
        $scope.models.lists.A.push({label: "Item A" + i});
        $scope.models.lists.B.push({label: "Item B" + i});
    }

    // Model to JSON for demo purpose
    $scope.$watch('models', function(model) {
        $scope.modelAsJson = angular.toJson(model, true);
    }, true);
});

Library can be installed via bower or npm: angular-drag-and-drop-lists

库可以通过bower或npm安装:angular-drag- drop-list

#6


4  

adapt-strap has very light weight module for this. here is the fiddle. Here are some attributes that are supported. There are more.

适配器带为此有非常轻的重量模块。这是小提琴。下面是一些支持的属性。有更多的。

ad-drag="true"
ad-drag-data="car"
ad-drag-begin="onDragStart($data, $dragElement, $event);"
ad-drag-end="onDataEnd($data, $dragElement, $event);"

#7


0  

small scripts for drag and drop by angular

小脚本的拖放角

(function(angular) {
  'use strict';
angular.module('drag', []).
  directive('draggable', function($document) {
    return function(scope, element, attr) {
      var startX = 0, startY = 0, x = 0, y = 0;
      element.css({
       position: 'relative',
       border: '1px solid red',
       backgroundColor: 'lightgrey',
       cursor: 'pointer',
       display: 'block',
       width: '65px'
      });
      element.on('mousedown', function(event) {
        // Prevent default dragging of selected content
        event.preventDefault();
        startX = event.screenX - x;
        startY = event.screenY - y;
        $document.on('mousemove', mousemove);
        $document.on('mouseup', mouseup);
      });

      function mousemove(event) {
        y = event.screenY - startY;
        x = event.screenX - startX;
        element.css({
          top: y + 'px',
          left:  x + 'px'
        });
      }

      function mouseup() {
        $document.off('mousemove', mousemove);
        $document.off('mouseup', mouseup);
      }
    };
  });
})(window.angular);

source link

来源链接