AngularJS - Dynamically creating elements that specify directives
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>
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, 2022Comments
-
Robert Christian almost 2 years
I have a setup like this:
- Controller
c
broadcasts evente
- Directive
d
listens fore
, and one
, writes to the DOM via append, and in so doing, creates new elements specifying a directived2
.
IE:
element.append('<directiveTwo ...>')
- Directive
two
is never called by Angular - When I inspect the DOM (and debug) I see that Controller
c
and directived
are doing their jobs, and I have newdirectiveTwo
elements.
What is missing? What needs to be done to trigger the directive
2
call after dynamically creating those elements? - Controller
-
bryan60 almost 8 yearsthank you for that alternative, just made it click for me how I'm SUPPOSED to be doing this.
-
Doug Chamberlain over 7 yearsMethod 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 almost 7 yearsJust 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.element(document.body).scope()));
Not the most elegant, but it works for our use case.