如果在transclusion之后添加,为什么指令下的动态元素具有错误的作用域

Why do dynamic elements under a directive have a wrong scope if added after transclusion?

本文关键字:动态 元素 作用域 有错误 指令 transclusion 之后 添加 为什么 如果      更新时间:2024-01-15

考虑以下示例,其中一个元素静态地包含在指令定义中,另一个元素稍后添加(使用jQuery):

angular.module('test', []).directive('transcludeThis', [function () {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        template: '<div id="transcluded" data-ng-transclude></div>'
    };
}]);
$(function() {
  angular.bootstrap(document, ['test']);
  $('#transcluded').append('<div>Dynamic (jQuery): </div>').find('*').each(function() {
      var $this = $(this);
      $this.append(angular.element($this).scope().$id);
  });
});
<transclude-this>
  <div>Static: </div>
</transclude-this>
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.3.10/angular.js"></script>

为什么动态元素不在transcluded范围内?

因为在创建指令的作用域时,该动态元素不存在。如果使用angular,则应在指令内部创建动态元素,然后将保持范围。