Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 688
Robert Christian Avatar asked Nov 17 '13 00:11

Robert Christian


People also ask

What are AngularJS directives?

What are Directives? At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.

How to compile an angular element using customdirectives?

In the 1st line I pass the template to `angular.element ()`, It’s the directive’s name <select-items> that we’ve set in the ` customDirectives` array I passed into <compile-me> directive. The returned value $el is now an angular element. In the 2nd line the angular element $el is passed to $compile. Compile is a function within the directive.

What are attribute directives in ngmodule?

Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components. Many NgModules such as the RouterModule and the FormsModule define their own attribute directives.

How to dynamically create content in an AngularJS application?

There’s a better way, cool and neat, to do it by using a great tool of AngularJS, $compile Using $compile we can dynamically create new content in an AngularJS application. I will present one way to accomplish it by packing the solution as a small independent consumable module.


1 Answers

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> 
like image 160
Andyrooger Avatar answered Sep 17 '22 20:09

Andyrooger