AngularJS克隆一个指令的元素并给出它自己的范围

时间:2014-06-17 08:54:25

标签: javascript angularjs angularjs-directive angularjs-scope

使用AngularJS,如果元素是transcluded指令的克隆,你如何为元素赋予自己的范围?

例如,说我有以下HTML:

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

以及以下指令:

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);
      }
    };
  }
]);

如何确保egg有自己的范围?

1 个答案:

答案 0 :(得分:1)

您创建一个新范围并将其链接:

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