user93 user93 - 1 year ago 41
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 Source

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

var myDirectives = [

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) {

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 =
    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.