user93 user93 - 2 months ago 12
AngularJS Question

Is it possible to populate directives in a page dynamically

I have a list directive selectors in an array I need to populate them dynamically in a page at runtime how do I proceed I am using angularjs 1.5.8

Answer

You should use $compile service to do that. For example, you have the following array of directives:

var myDirectives = [
     "<my-app-directive-one></my-app-directive-one>",
     "<my-app-directive-two></my-app-directive-two>",
     "<my-app-directive-three></my-app-directive-three>"
];

Then you can compile them individually or in a loop and insert to you html like this:

TestDirective.$inject = ["$compile"];
function TestDirective($compile) {
    return {
        restrict: "E",
        link: link
    };

    function link(scope, element) {
        element.append($compile(myDirectives[0])(scope));
    }
}

I used the scope of a parent directive (used as a directive sandbox), but you can create a child scope (scope.$new()) or an isolated scope (scope.$new(false)) for it.

If you array looks like this:

var myDirectives = ["my-app-directive-one", "my-app-directive-two"];

then you can simply do the following transformation:

myDirectives = myDirectives.map(
    function(directive) {
        return "<" + directive + "></" + directive + ">";
    }
);

Simpler solution

You can just use ng-if instead of ng-show, if you can place all the directives on the same page before runtime. It will solve you perfomance issues, since ng-if removes all the watchers when destroying a directive.

Comments