Angularjs 中遇到错误:[ngTransclude:orphan] 在模板中非法使用 ngTransclude 指令

Encountering Error in Angularjs : [ngTransclude:orphan] Illegal use of ngTransclude directive in the template

我得到了这段代码,其中一个指令在一个指令中:

<script>

app.directive('testChart', function () {
            return {
                restrict: 'E',
                transclude: true,
                controllerAs: 'chartCtrl',
                template: '<div><ng-transclude></ng-transclude></div>',
                controller: ['$scope', '$element', '$attrs', '$compile', function ChartController($scope, $element, $attrs, $compile) {
                    $scope.chartId = $scope.$id;
                    let content = angular.element('<div><div id="container'+ $scope.chartId + '"></div></div>');
                    $element.append(content);
                    $compile($element.contents())($scope); //<---- recompilation 
                    var html = $element.html();
                    var hc = Highcharts.chart('container' + $scope.chartId, {

                    });
                }]
            };
        })      
</script>

https://www.w3schools.com/code/tryit.asp?filename=FIKIWZCHGPPD

添加模板时:<ng-transclude></ng-transclude> 到模板时出现错误:Error: [ngTransclude:orphan] Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found.

这个错误的原因是什么?我已经查看了具有相同问题的其他问题,但我无法将这些解决方案应用于我的问题。

testChart 指令中的重新编译行导致问题。在执行该行之前 angular 已经创建(&编译)testChart 指令为:

<div ng-transclude=""></div>

稍后附加一些元素并对其进行编译时将其视为具有 ng-transclude 指令的简单 div 元素,默认情况下显示 Orphan ngTransclude Directive 错误。因此,只需从指令定义中删除该行,其他一切都可以正常工作。所以你的指令定义将是(不包括重新编译行)

app.directive('testChart', function() {
  return {
    restrict: 'E',
    transclude: true,
    controllerAs: 'chartCtrl',
    template: '<div><ng-transclude></ng-transclude></div>',
    controller: ['$scope', '$element', '$attrs', '$compile', function ChartController($scope, $element, $attrs, $compile) {

      $scope.chartId = $scope.$id;
      let content = angular.element('<div><div id="container' + $scope.chartId + '"></div></div>');
      $element.append(content);
      //$compile($element.contents())($scope); //<---- recompilation 
      var html = $element.html();
      console.log(html);
      var hc = Highcharts.chart('container' + $scope.chartId, {

      });
    }]
  }; 
})

Working plunker

在某些需要强制编译的情况下,在将其附加到此处使用 ng-transclude 的指令模板之前执行此操作。