AngularJS: using $ compilation to add html to web page

I have a dynamic web page that is generated by previous entries that the user has made. This means that you can view a list of possible inputs that they could choose by adding them to the html in the directive.

So in order for my ng tags to work, I need to run this big chunk of html through compile in order for them to still work. This works great, now the problem is that I am trying to execute more complex fields that use custom directives or jquery classes that just refuse to work as expected after being submitted via $ compilation.

For example -

<div data-j-signature="obj.Test" data-pen-color="#0000ff" data-line-color="#00000" style="border:1px #000 solid;"></div><div class="col-sm-11">


This uses a well-used angular library called JSignature and will work fine when placed somewhere in my web page, but not when the compilation process transitions.

I am not necessarily looking for an answer for this particular problem, as I believe it will be a persistent problem with a lot of fields that I am trying to add. Does anyone have general advice on how to get around this? Is there an alternative that I can't see?

Here is my html -

<div ng-repeat="Question in Questions">


Here is an important part of what my directive does at the end by concatenating many lines of html together -

var compiledHtml = $compile(stringOfHtml)(scope);



source to share

1 answer

This uses jquery datepicker and will work fine, but not when added and then compiled in my directive.

And that's really the core of your problem. You cannot expect jQuery plugins to function correctly inside an Angular application, simply because their lifecycles are not very good. I'll explain better.

When the app starts, some HTML with Angular directives and binding is parsed and compiled with Angular. I'm fine. At this point, your jQuery plugins will probably even initialize correctly, because usually they should just have DOM rendering. However, what happens when you add newly compiled dynamic HTML? Angular will pick it up well because you are calling $compile

. But jQuery can get desynchronized and never update plugins.

This is the main reason why you shouldn't use jQuery the way we're used to. Ideally, jQuery usage (and DOM manipulation in general) should be limited to custom directives only. This is the only way to be 100% sure that both Angular and jQuery are updating / initializing their materials at the right time.

So .. Do you need a dumper? Big! There are many Angular directives (like Angular's datepicker UI) that just brings jQuery plugins into a bind function, making it compatible with Angular workflow loops and digests.



All Articles