0

Ok, I've seen similar questions on SO but still don't understand this issue.

I have a directive for date input, using ngModelController. I have another directive, to which you can pass the model controller, and it checks if the model has errors, and sets appropriate classes to the element.

So the markup looks like this:

<form name="myForm">
    <div class-validation="myForm.date">
        <date-input ng-model="date" name="date"></date-input>
    </div>
</form>

Since we have date-input inside of our form, and it has the name attribute and ng-model, the ngModelController will be added to myForm under the name date, which is exactly what we pass to class-validation directive.

Now the problem is, if I use templateUrl for my date-input directive, the class-validation directive receives undefined. But when I use inline template instead, everything works as expected.

Here is a Plunker that demonstrates the problem exactly. http://plnkr.co/edit/Cygawxjp4WN9xRbTEXWU?p=preview

Comment out line 41 and uncomment line 42 in script.js to see the problem. The validation doesn't work and if you open browser console, you'll see that class-validation parsed myForm.date as undefined.

Why is this happening? I am guessing that requiring template from an url is async operation, but it shouldn't make a difference to the developer. I wasted hours and hours trying to find out what's causing this. Thanks.

Paritosh
  • 11,144
  • 5
  • 56
  • 74
tuks
  • 800
  • 3
  • 11
  • 27
  • for the record, you are correct, this occurs because `templateUrl` is async, and the element isn't present in the DOM at the time that the directive is parsed. there isn't currently a solution or workaround that is foolproof. – Claies Sep 15 '16 at 12:26
  • 1
    from the angular documentation: "Because template loading is asynchronous the compiler will suspend compilation of directives on that element for later when the template has been resolved. In the meantime it will continue to compile and link sibling and parent elements as though this element had not contained any directives." – Claies Sep 15 '16 at 12:34
  • If you want to access DOM in link, you should load a template manually with $templateRequest instead of templateUrl. – Estus Flask Sep 15 '16 at 12:34
  • @Claies Thanks for clarification. I missed that part about suspending compilation. So I guess the only option is to write directive templates inline. – tuks Sep 15 '16 at 12:40

0 Answers0