模板未应用于指令内的指令

Template doesn't get applied for a directive inside a directive

我在一个看起来像这样的指令中得到了一个指令:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<body ng-app="myApp">

<test-directive></test-directive>

<script>

var app = angular.module("myApp", []);

app.directive("testDirective", ["$compile", function($compile) {
    return {
        restrict: 'AE',
        template: '<div>just a test</div>',
        link: function (scope, element, attrs) {

            let autocomplete = $compile('<test-chart></test-chart>');
            let content = autocomplete(scope);
            element.append(content);
        }
    };
}]);

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

                    var hc = Highcharts.chart('container', {

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

</body>
</html>

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

我遇到的问题是当内部指令尝试使用以下方法初始化高图时:

var hc = Highcharts.chart('container', { });

这会发出 highchart 错误 #13,即 highchart 无法找到要在其上创建图表的元素。在这个例子中:<div id="container">

查看内部指令的控制器内部文档,它似乎缺少指令的模板。这就是 highchart 排名第 13 的原因。

为什么没有应用内部指令模板?

仔细看看你的 testDirective 的链接函数:

let autocomplete = $compile('<test-chart></test-chart>');
// Your test chart is detached here and thus its controller can't find container in the DOM
let content = autocomplete(scope);
// This line of code is never executed because the previous one throws that's why you never see your test chart being appended to the DOM
element.append(content);

要解决此问题,您首先需要将 autocomplete 附加到 DOM。然后才执行编译和链接。基本上你可以这样做:

let content = angular.element('<test-chart></test-chart>');
element.append(content);
$compile(element.contents())(scope);