克隆angularjs中的html元素

时间:2013-03-15 15:59:50

标签: angularjs

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

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

有什么建议吗?

2 个答案:

答案 0 :(得分:10)

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

假设您在<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
}

答案 1 :(得分:2)

我有同样的问题包装克隆我的节点的库。这是我的解决方案:

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