1

I have a directive and inside it's template is a <img> element and I want to execute a custom method that is within my directives scope:

<my-directive>
    <!-- my directives template -->
    <p>...</p>
    <img onload="myScopeMethod()">
    <p>...</p>
    <!-- my directives template -->
</my-directive>

I found this Get width height of remote image from url but this works only if im applying it to a directive that works on the <img> element.

The directives purpose is to show a widget that allows me to manipulate the image (scale it by dragging a slider) but I somehow need to get it's original size.

How can I get it to execute the method from my controllers scope?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

You would generally want to take your load handler function out of the template itself and stick it in the link function. From there it kind of depends on your directive and whether you are using an isolate scope, inherited scope, or the same scope as the parent.

If you have a scope key in your directive definition object and it's set to an object literal, then you are using the isolate scope. In that case, you'll need to pass it in somehow, and the most straightforward way is to use the '&' option.

If you don't have a scope key or have a scope key and it's set to a boolean value you're using the same scope or an inherited scope. In this case, all you need to do is call $scope.originalScopeMethod() and it will either call it on the scope or find it in the prototype chain.

Here's an example with the three different scenarios. The table at the bottom is being fed from the 'main' controller scope while the small numbers are fed from the directive scope.

If it were me I'd probably go with either isolate or inherited scope so you can keep track of multiple images separately a little easier. The shared scope version in my example would only work for a single image, but you could make it work with an array or hash if you really wanted.

Let me know if I misunderstood your question in any way.

soydeedo
  • 41
  • 3
  • Hey, thanks for your long answer and the great example. Honestly, I have not yet fully understood the code, I'll give it a try today or tomorrow as I find the time to do so. I'm pretty sure it's doing what I want I just couldn't make it work in my project yet. –  Jan 19 '15 at 14:31
  • If you want to post what you have of your directive so far I could probably help point you in the right direction. – soydeedo Jan 20 '15 at 17:52