Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

AngularJS - Dynamically creating elements that specify directives

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?

question from:https://stackoverflow.com/questions/20025526/angularjs-dynamically-creating-elements-that-specify-directives

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...