2017-07-27 93 views
1

我有一個指令內的指令,看起來像這裏面的:模板不應用一個指令一個指令

<!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

我遇到的問題是,當內指令試圖初始化使用highchart:

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

這將發出錯誤highchart#13這是當highchart無法找到創建圖表的元素。在這個例子中:<div id="container">

看看內部指令的控制器內的文件,它似乎缺少指令的模板。這就是爲什麼Highchart獲得#13。

enter image description here

爲什麼沒有內部指令模板得到應用?

回答

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); 
相關問題