Access directive's isolate scope from within transcluded content

后端 未结 3 1786
太阳男子
太阳男子 2021-02-13 02:35

I\'m not sure if this is actually possible, but I\'m essentially wanting a reverse of the \'&\' isolate scope in AngularJS. Here is a Plunkr to demonstrate.

Basicall

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-13 03:19

    Although possible, the solution I present is a hack, as it uses a scope internal variable, $$prevSibling.

    Inside your transcluded content, you are inside the transcluded scope. The directive's isolate and transcluded scopes are siblings. To get from the transcluded scope to the isolate scope, you can use $$prevSibling. (To get from the isolate scope to the transcluded scope, you can use $$nextSibling.)

    So, this hack will work:

    Invoke the Directive Action
    

    To call a method on the controller scope, you need to specify that using & as @ganaraj already demonstrated:

    
    

    Then in your directive:

    scope: { controllerAction: '&' },
    template: ... +
       '' ...
    

    Plunker


    With ng-repeat (see Samuel's comment), each item creates a child scope of the transcluded scope. In the picture below, I only show one item to keep the picture smaller. Reverse the $$nextSibling brown arrow for $$prevSibling.

    enter image description here

    So the hack to get to method action() defined on the isolate scope from an ng-repeat child scope is


    Update for Angular v1.3+:

    Since Angular v1.3, the transcluded scope is now a child of the directive's isolate scope – they are no longer siblings. So to get from the transcluded scope to the isolate scope, use $parent.

    With ng-repeat, each item still creates a child scope of the transcluded scope:

    enter image description here

    But to get to method action() defined on the isolate scope from an ng-repeat child scope, we now use

提交回复
热议问题