AngularJS - Dynamically creating elements that specify directives

86,758

See $compile. You can use this service similarly to this:

var newDirective = angular.element('<div d2></div>');
element.append(newDirective);
$compile(newDirective)($scope);

This will perform the compilation and linking of your new element, and set d2 into action.

However you may find it simpler and more angular if you can somehow rewrite your original directive in terms of other built in directives like ng-repeat or ng-include that will perform the compile and link for you.

If your directive is simple enough it could just do something along the lines of adding to an array when hearing your event, and specify a template like

<div ng-repeat="evt in recordedEvents">
    <div d2="evt"></div>
</div>
Share:
86,758
Robert Christian
Author by

Robert Christian

Software architect and polyglot developer currently using S/O for the Java, Python, NodeJS, Javascript, Vert.x, client MVC frameworks, open source, cloud platform, and algorithms communities.

Updated on July 09, 2022

Comments

  • Robert Christian
    Robert Christian almost 2 years

    I have a setup like this:

    • Controller c broadcasts event e
    • Directive d listens for e, and on e, writes to the DOM via append, and in so doing, creates new elements specifying a directive d2.

    IE: element.append('<directiveTwo ...>')

    • Directive two is never called by Angular
    • When I inspect the DOM (and debug) I see that Controller c and directive d are doing their jobs, and I have new directiveTwo elements.

    What is missing? What needs to be done to trigger the directive 2 call after dynamically creating those elements?

  • bryan60
    bryan60 almost 8 years
    thank you for that alternative, just made it click for me how I'm SUPPOSED to be doing this.
  • Doug Chamberlain
    Doug Chamberlain over 7 years
    Method 2: eliminates your abliity to control scope easily, and ng-repeat is very heavy, at our office we are actively removing and refactoring templates that use ng-repeat/ng-click/ng-keypress etc... to dom manipulation and element handlers.
  • Phil Gibbins
    Phil Gibbins almost 7 years
    Just in case anyone needs help with this approach, I firstly combined into one line, but had to define scope and the $compile function: define $compile: window.$compile = angular.element(document.body).injector().get('$compile'); compile html: $(elem).append($compile(angular.element(html))(angular.eleme‌​nt(document.body).sc‌​ope())); Not the most elegant, but it works for our use case.