Paul Fleming Paul Fleming - 5 months ago 11
Javascript Question

Angular 1.x consuming outer scope within directive template body

Given a third party directive

tpd
with isolate scope (closed source for argument's sake), take the following markup for example:

<div>
<tpd>
<div>{{tpdScopeField}}</div>
<div>{{outerScopeField}}</div>
</tpd>
<div>{{outerScopeField}}</div>
</div>


This will output something similar to:

<div>
<tpd>
<div>tpdScopeFieldValue</div>
<div></div>
</tpd>
<div>outerScopeFieldValue</div>
</div>


How can one communicate effectively with the outer/parent scope in markup?

Another example would be trying to call a function (on-something event) of the outer scope:

<div>
<tpd>
<button ng-click="outerScopeEventHandler(someArgs)">Click me!</button>
</tpd>
<div>{{outerScopeField}}</div>
</div>

Answer

If the property is available in parent, this code will do:

<div>
    <tpd>
        <div>{{tpdScopeField}}</div>
        <div>{{$parent.outerScopeField}}</div>
    </tpd>
    <div>{{outerScopeField}}</div>
</div>

And similarly $parent.functionToCall(args) will call the parent scope method.

Comments