我在一个看起来像这样的指令中得到了一个指令:
<!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', { });
这会发出一个高图错误#13,当高图无法找到创建图表的元素时。在此示例中:<div id="container">
查看控制器内部指令的文档,似乎缺少指令的模板。这就是为什么高图获得#13。
为什么不应用内部指令模板?
答案 0 :(得分:1)
仔细查看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);