George Reith
George Reith

Reputation: 13476

AngularJS clone a directive's element and give its own scope

With AngularJS how do you give an element its own scope when it is a clone of a transcluded directive?

E.g., say I have the following HTML:

<body>
   <chicken></chicken>
</body>

and the following directive:

app.directive('chicken', [
  '$rootElement',
  function($rootElement) {
    return {
      restrict: 'E',
      replace: true,
      transclude: true,
      template: '<div class="chicken" ng-transclude></div>',
      scope: {},
      link: function(scope, element, attrs) {
        scope.nature = 'timid';
        var egg = element.clone();
        $rootElement.append(egg);
      }
    };
  }
]);

How do I ensure that egg has its own scope?

Upvotes: 1

Views: 865

Answers (1)

Michael Kang
Michael Kang

Reputation: 52847

You create a new scope and link it:

  link: function(scope, element, attrs) {
    scope.nature = 'timid';
    var egg = element.clone();
    var childScope = $rootElement.scope().new();
    $compile(egg)(childScope);
    $rootElement.append(egg);
  }

Upvotes: 1

Related Questions