Why ng-transclude's scope is not a child of its directive's scope - if the directive has an isolated scope?

前端 未结 3 1488
醉酒成梦
醉酒成梦 2020-11-30 05:38

Given a directive (container1) with transclude and an isolated scope, when the directive is linked then I have these scopes:

Scope 004                   


        
相关标签:
3条回答
  • 2020-11-30 06:03

    Why ng-transclude's scope is not a child of its directive's scope if the directive has an isolated scope?

    ng-transclude designed to allow directives to work with arbitrary content, and isolated scopes are designed to allow directives to encapsulate their data.

    If ng-transclude didn't preserve scopes like that, any arbitrary content that you're transcluding would need to know the implementation details of your directive (i.e. it would need to know what's available on the isolated scope you created).

    If it's not a bug, how can a container directive pass data to it's content, if not by setting attributes like I tried.

    If the container directive and contained directives are coupled - i.e. you wrote both of them and need them to act together - then they should communicate via a shared controller.

    If the container directive is supposed to inject content into the scope of the children (e.g. ng-repeat), then you shouldn't be using an isolated scope.


    The angular documentation is quite clear on what the behaviour is supposed to be:

    "In a typical setup the widget creates an isolate scope, but the transclusion is not a child, but a sibling of the isolate scope. This makes it possible for the widget to have private state, and the transclusion to be bound to the parent (pre-isolate) scope."

    0 讨论(0)
  • 2020-11-30 06:13

    The top answer is only correct for Angular up to v1.2.

    Since Angular v1.3 the behaviour has changed, and it now behaves exactly as described in the "I expected" part of the question, making this question obsolete for Angular v1.3+.

    Source: https://github.com/angular/angular.js/commit/fb0c77f0b66ed757a56af13f81b943419fdcbd7f

    0 讨论(0)
  • 2020-11-30 06:15

    you can manually transclude the child element

    link: function(scope, element, attrs, ctrl, transclude) {
        transclude(scope, function(clone, scope) {
            element.find('.transclude-placeholder').append(clone);
        });
    }
    
    0 讨论(0)
提交回复
热议问题