Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone html element in angularjs

Tags:

angularjs

I'm trying to implement drag and drop system in angularjs.

I want dragged object to be cloned on drag start. However I have no idea how to clone an element along with it's scope and linked controller in angularjs?

Any suggestions?

like image 276
Szymon Wygnański Avatar asked Mar 15 '13 15:03

Szymon Wygnański


2 Answers

Cloning DOM elements as it is usually done for drag & drop is not recommended with Angular. Instead, clone your object model.

Let's say you display items in an <UL> and have another dragged item visible only while dragging:

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

and in the controller, make a copy of the item to drag into 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
}
like image 93
Mart Avatar answered Oct 04 '22 09:10

Mart


I had the same issue wrapping a library which cloned my nodes. This is my solution:

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

like image 31
A. Matías Quezada Avatar answered Oct 04 '22 07:10

A. Matías Quezada