alobeejay
alobeejay

Reputation: 257

AngularJS - Clone element with functionality

I have a directive in which I want to clone a DOM element that they are exactly the same with all bindings. That when one of them changes, the other one changes as well. Is that possible? I understand I somehow have to compile the copied element but are they interconnected with the changes then?

angular.module('app').directive('test', function ($compile) {
  return {
  restrict: 'A',
  link: function (scope, element, attrs) {

   angular.element(document).ready(function () {

      var $header = angular.element(XXX).clone();
      // $compile($header)(scope); // not sure about this one. it doesn't work
      var $newHeader = angular.element(YYY).append($header);

    }
  }
});

Upvotes: 2

Views: 9748

Answers (1)

Stephane Janicaud
Stephane Janicaud

Reputation: 3627

Here is a small example on how to achieve this.

This example use a controller with a displayContent method that display content of an element on click.

We search inside the div element with test directive the existing <p> element with ng-click directive, clone it, change its content and append it to our div parent element.

Before appending this element copy, it needs to be compiled so that Angular will recognize its bindings.

index.html

<!doctype html>

<html lang="en" ng-app="app">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body ng-controller="SampleController as ctrl">     
    <div test>
        <p ng-click="ctrl.displayContent($event)">Dummy</div>
    </div>
</body>
</html>

script.js

angular.module('app', []);

angular.module('app').controller('SampleController', function ($scope) {

    var ctrl = this;

    ctrl.displayContent = function($event) {
        alert($event.currentTarget.innerHTML);
    }     

});

angular.module('app').directive('test', function ($compile) {
  return {
      restrict: 'A',
      link: function (scope, element, attrs) {

           // Find <p> element inside our elment with `test` directive
           var pElement = element.find('p');
           // Clone <p>
           var pElementCopy = pElement.clone();
           // Change its content
           pElementCopy.html("Foo");
           // In order ng-click to work on this copy, you must compile it
           // If you remove the following line, then ng-click won't work
           $compile(pElementCopy)(scope);

           element.append(pElementCopy)
      }
    }
});

Link to the plunker : https://plnkr.co/edit/T4elaGJMgMtxX6bKJHf0?p=preview

Upvotes: 2

Related Questions