Angularjs 使用ng transclude从my指令的HTML模板执行两次脚本标记

Angularjs 使用ng transclude从my指令的HTML模板执行两次脚本标记,angularjs,angularjs-ng-transclude,Angularjs,Angularjs Ng Transclude,我有一个指令,将从CMS获取的一些HTML转换到我的AngularJS应用程序中。当我向指令中添加脚本标记并向其添加控制台消息时,该消息将被记录两次 这是我的指示: angular.module('my-directive', []) .directive('myDirective', function () { return { restrict: 'E', replace: false, transclude: true, temp

我有一个指令,将从CMS获取的一些HTML转换到我的AngularJS应用程序中。当我向指令中添加脚本标记并向其添加控制台消息时,该消息将被记录两次

这是我的指示:

angular.module('my-directive', [])
  .directive('myDirective', function () {
    return {
      restrict: 'E',
      replace: false,
      transclude: true,
      template: '<section class="my-directive" ng-transclude> 
         </section>'
    };
  });
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<section ng-transclude ng-if="run"></section>',
        link: function (scope) {
            //----your scripts
            console.log("ABCD");
        }
    };
angular.module('my-directive',[])
.directive('myDirective',函数(){
返回{
限制:'E',
替换:false,
是的,
模板:'
'
};
});
我使用它的方式如下:

<my-directive>
  <script>
    console.log("ABCD");
  </script>
</my-directive>

控制台日志(“ABCD”);
预期结果:“ABCD”记录一次

实际结果:“ABCD”记录两次


有人能解释为什么会发生这种情况吗?

答案是第一次出现在
文档中。加载
指令中的
,它完全不取决于指令

第二次加载指令,这样就有了两次控制台

如果要选中“使用
$timeout
延迟加载模板”:

打开浏览器控制台

    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<section ng-transclude ng-if="run"></section>',
        link: function (scope) {
            //----your scripts
            console.log("ABCD");
        }
    };