Dynamically registering a directive at runtime

Typically, directives are registered in a module using the method directive

:

.directive('MyDirective', function (MyDep) {
    return {
        restrict: 'E',
        template: '<div></div>',
        controller: function ($scope) {
        }
    }
});

      

However, what if I want to dynamically register directives at runtime? For example, let's say a user retrieves the following data from the server:

{
    directives: {
        dir1: {
            restrict: 'E',
            template: '<div></div>',
        },
        dir2: {
            restrict: 'E',
            template: '<div></div>',
        }
    }
}

      

Can I use this data to dynamically register new directives for my application? If successful, I should be able to dynamically generate and $compile

HTML that depends on them.

+3


source to share


1 answer


This is a subset of the "lazy loading Angular artifacts" (I researched here and there are other resources). The idea is to use a function config

to "steal" $compileProvider

( ref ) and then call $compileProvider.directive(...)

on demand based on your data.

Rough sketch of the idea:

var cachedCompileProvider;
angular.module(...).config(['$compileProvider', function($compileProvider) {
    cachedCompileProvider = $compileProvider;
});

      



And then (for example, from the inside, where there is access to $http

):

$http.get(...).then(function(response) {
    angular.forEach(response.data.directives, function(dirDefinition, dirName) {
        cachedCompileProvider.directive(dirName, dirDefinition);
    });
});

      

(Of course, you cannot get controller functions from the JSON response as above, you will have to use other methods - but hopefully you get the idea.)

+8


source







All Articles