Reputation: 93
I need to create a directive inside angular service and then on an event insert element with that directive into dom and compile it, the inserting and compiling seems to be working fine, but it seems that directives created dynamically from inside angular (controller, service or wherever) don't register or something.
Here's a simplified version of my current code
var dirs = angular.module('dirs', []);
dirs.factory('directiveCreator', function($rootScope) {
var creator = {};
creator.addDirective = function(config) {
dirs.directive(config.name, function() {
return {
restrict: config.restrict,
template: config.template,
replace: config.replace,
}
});
//insert element with the directive above into DOM on this event and compile
$rootScope.$broadcast('directive.added');
}
return creator;
}
The directive is added to invokeQueue properly on the module, but it doesn't work at all, am I missing something?
Upvotes: 1
Views: 650
Reputation: 42736
you need to capture the $compileProvider
and then use the directive
method instead of using the moduleObj.directive
method
var dirs = angular.module('dirs', []);
dirs.config(function($compileProvider){
dirs.compileProvider = $compileProvider;
});
then when you need to dynamically include the new directive
creator.addDirective = function(config) {
dirs.compileProvider.directive(config.name, function() {
return {
restrict: config.restrict,
template: config.template,
replace: config.replace,
}
});
//insert element with the directive above into DOM on this event and compile
$rootScope.$broadcast('directive.added');
}
This is lazy loading, Here is an article that I found helpful in doing such things
Upvotes: 3