Giraldi
Giraldi

Reputation: 17291

AngularJS: Cannot get innerHTML of dynamic element within a directive

I am trying to get the innerHTML of an element with dynamic content form within a directive.

Below is the Plunker:

https://plnkr.co/edit/rXVin1LPWzpH4eMqZc7R?p=preview

The one in green is the expected result. The one in red is the part I hope to get working.

Notice on the console.log result, the outcome for el.innerHTML is {{ item }}. Why isn't it getting the text that is bound to it? How do I get it to work?

Upvotes: 1

Views: 785

Answers (1)

tasseKATT
tasseKATT

Reputation: 38490

It's because Angular hasn't finished processing the child templates from ng-repeat.

You can warp the code in scope.$evalAsync to make it work:

link: function(scope, element, attr, content) {

  scope.$evalAsync(function() {

    var el = element[0];

    // Code
  });
}

More on $evalAsync vs $timeout: https://stackoverflow.com/a/17303759/2887841

Upvotes: 4

Related Questions