这是一个 plnkr http://plnkr.co/edit/Q5oD65wSvBAemf5BCDL7?p=preview
在这种情况下,您可以使用 $compile (您仍然需要示例中的 $scope,但我猜 $compile 几乎可以回答您的问题),
var $compile = chartsInjector.get("$compile");
console.log("$compile=",$compile);
var chartsDirective = $compile("<div charts></div>");
console.log(chartsDirective);
...
var blockapp = angular.module('blockApp', []);
blockapp.run(function(){
// create a new injector
var chartsInjector = angular.injector(['ng', 'angularCharts']);
console.log("chartsInjector=",chartsInjector);
var $compile = chartsInjector.get("$compile");
console.log("$compile=",$compile);
var chartsDirective = $compile("<div charts></div>");
console.log(chartsDirective);
})
请注意,您将在此处创建多个注入器。
注入器 1) 由 ng-app 创建
<body ng-app="blockApp">
注入器 2) 由 angular.injector() 创建
var chartsInjector = angular.injector(['ng', 'angularCharts']);
整个代码
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script type="text/javascript">
// creating the angularcharts
angular.module('angularCharts', []).directive('charts', function(){
return function(){}
});
// creating blockapp
angular.module('blockApp', []).directive('', []);
// retrieving the created blockapp
// NOTE! ng-app will create a new injector for blockapp
var blockapp = angular.module('blockApp', []);
blockapp.run(function(){
// create a new injector
var chartsInjector = angular.injector(['ng', 'angularCharts']);
console.log("chartsInjector=",chartsInjector);
var $compile = chartsInjector.get("$compile");
console.log("$compile=",$compile);
var chartsDirective = $compile("<div charts></div>");
console.log(chartsDirective);
})
</script>
</head>
<body ng-app="blockApp">
</body>
</html>
plnkr http://plnkr.co/edit/Q5oD65wSvBAemf5BCDL7?p=preview