User-8017771
User-8017771

Reputation: 1612

Access the html content of directive in parent controller

I have an overlay and I set its position manually by accessing the html content and getting the height, width etc.

Now, I have converted the overlay to a directive. But I cant access the html content of the directive itself to update the position.

What have I tried: I tried using replace:true in the directive. But when I try to access the div - I still get the directive element rather than the directive html content. Eg: My Directive:

<my-dir somevalue='something'>
</my-dir>

Directive HTML:

<div class="overlay">
<span>{{somevalue}}</span>
</div>

Now when I try to access the directive element, I want to access the class 'overlay'

Upvotes: 0

Views: 67

Answers (1)

MikeJ
MikeJ

Reputation: 2324

First, in your directive template, you should probably be referring to somevalue, not something, since presumably somevalue is what's being set on the directive's scope.

Then to access the .overlay child element, in your directive's link function you can use the querySelector method on the directive's native DOM element, like so:

link: function (scope, el, attrs) {
  var overlayElement = el[0].querySelector('.overlay');
}

The el that's passed into the link function is the jqLite-wrapped directive element, so el[0] gets you the native DOM element.

Here's a fiddle demonstrating this approach.

Upvotes: 1

Related Questions