1

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.