9

我正在尝试在 angularjs 中实现拖放系统。

我希望在拖动开始时克隆拖动的对象。但是我不知道如何在angularjs中克隆一个元素及其范围和链接控制器?

有什么建议么?

4

2 回答 2

10

不建议使用 Angular 克隆 DOM 元素,因为它通常用于拖放。相反,克隆您的对象模型。

假设您在 an 中显示项目,<UL>并且只有在拖动时才能看到另一个拖动的项目:

<ul>
    <li ng-repeat="item in items" class="{{item.shadow}}">{{item.text}}</li>
<ul>
<div ng-show="draggedItem != null">{{draggedItem.text}}</div>

并在控制器中,复制要拖动到 draggedItem 中的项目:

$scope.items = [{text:"First"}, {text:"Second"}];
$scope.shadowItem = null; // Item at the original position
$scope.draggedItem = null; // Clone item being moved

$scope.dragStart = function(item) {
    $scope.shadowItem = item;
    $scope.draggedItem = angular.copy(item);
    item.shadow = "shadow"; // set a CSS class to change its look
    // From now on, the DIV is dragged around
}

$scope.drop = function() {
    // Save the new item position
    $scope.draggedItem = null; // Makes the dragged clone item disappear
    $scope.shadowItem.shadow = ""; // give the item its normal look back
}
于 2013-03-16T12:10:20.677 回答
3

我在包装一个克隆我的节点的库时遇到了同样的问题。这是我的解决方案:

angular.module('my-module')
.directive('mqAllowExternalClone', function($compile) {
  return {
    link: link,
  };

  function link(scope, elem, attr) {
    var element = elem[0];
    var original = element.cloneNode;
    element.cloneNode = patch;

    function patch(deep) {
      var clone = original.call(element, deep);

      // You can remove this two lines and the result
      //   will be more or less the same.
      // In my case I need it for other reasons
      clone.removeAttribute('mq-allow-external-clone');
      clone.cloneNode = patch;

      $compile(clone)(scope);
      return clone;
    }
  }
});

https://gist.github.com/amatiasq/ae6fce9acf74589ef36d

于 2015-05-28T09:57:26.327 回答