How to load angularjs directive use $ injector
I am trying to use a directive from other modules being loaded angular.injector
, but angular cannot understand the directives that are in other_module
.
In my main file, I declare my module.
angular.module('blockApp', []).directive('', []);
In the second file, I am trying to add angularCharts as a dependency:
var otherBlock = angular.module('blockApp');
otherBlock.run(function() {
angular.injector(['ng', 'angularCharts']);
});
Then I use directives angularCharts
, but angularjs cannot identify them. I know we have to add dependent modules when we declare a module, but this is a special case.
source to share
here a plnkr http://plnkr.co/edit/Q5oD65wSvBAemf5BCDL7?p=preview
In this case, you can use the $ compilation (you will still need the $ scope from the example, but the $ compilation pretty much answers your question, I think),
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);
})
note that you will create some injectors here.
injector 1) generated by ng-app
<body ng-app="blockApp">
injector 2) generated by angular.injector ()
var chartsInjector = angular.injector(['ng', 'angularCharts']);
all code
<!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>
source to share