StevieP
StevieP

Reputation: 401

Compiling angular editor directive

Some (advanced?) angular is making my head hurt.

The goal is to extend a WYSIWYG HTML editor to allow users to insert certain angular directives into arbitrary HTML content. I have chosen medium-editor and its angular-medium-editor wrapper (but I'm not wedded to that if there are better solutions).

This Plunk shows how the editor directive is instantiated and activated (using an editable attribute). The toolbar is customised to include a button which adds a custom directive around selected text: <my-custom-directive class="bg-info"> ... </my-custom-directive>. (For demonstration, the custom directive wraps (transcludes) its contents in a button which triggers an alert when clicked).

I'm having problems with (re-)compiling the editor's content so that the directives inside the editor compile. Using $compile(element.contents())(scope) throws ngTransclusion:orphan errors for directives which uses transclusion. (I understand this is due to angular already having made the transclusion by the time the editor's link function is called.)

I cannot refactor all potential custom directives to not use transclusion.

What pattern can I use to successfully compile arbitrary editor content (which may include many different directives), ideally whenever that content changes, or at least when the editing is finished? Is this one of the "fringe cases" where the use of $compile is justified? If so, how do I use it?

Upvotes: 0

Views: 205

Answers (1)

StevieP
StevieP

Reputation: 401

This question and answer made me realise that the way to do this is to $compile only the inserted element when it is inserted, rather than recompiling the whole section.

Handily, rangy's classApplier module allows for an onElementCreate callback which can be used to compile the custom directive as it is added.

Here's the working plunker.

Upvotes: 0

Related Questions