Angularjs - ng-model undefined

2019-07-11 14:39发布

问题:

I am building a rather complex directive in which I need access to ng-model on a specific element in the template which is enclosed into ng-if directive... I have a plunker and the explanation on how to see the issue is below.

In the .compile function of the directive I have a line of code that looks like this

ngModel = elm.find('textarea').controller('ngModel');
console.log(ngModel);

In my template, I have a something like this:

<div  ng-if="views.view">
    <textarea ng-model="exp.val"></textarea>
</div>

When I use ng-show my console.log gets an object of ng-model, no problem ...

The requirement is very strict however and I have to use ng-if. When I use ng-if my console log gets undefined

The actual working version of the problem exists in this plunker

If you change the line 6 in template.html into ng-if you can see the behavior.

How do I have to write this line to retrieve the model when inclosed in ng-if.

ngModel = elm.find('textarea').controller('ngModel');

I also tried using attach-if directive by Simon Sparks. This directive is pretty cool, it preserves the scope unlike ng-if so if you specifically need to not render HTML but you need to preserve scope it works great.

I still have the same problem with invoking ngModel as I am doing it but because of applying custom filters in the directive I have to update ng-model in this way.

I am this one step away from finishing this directive. Hoping someone can help.