angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

ng-transclude should not create new sibling scope.

Open mbykovskyy opened this issue 12 years ago • 69 comments

This is more of a change request and I would like to see what other people think.

In my humble opinion ng-transclude should not create it's own scope or at least have a way to prevent it from doing so. The reason behind this is that a directive which requests transclusion already has means to specify whether or not it wants to have a scope or an isolated scope or no scope at all. It uses ng-transclude directive to mark where it wants to insert the content. When ng-transclude creates it's own sibling scope it kind of breaks the expectations of the directive which defines what kind of scope it wants and there comes the manifestation of the popular 'value' vs 'object.value' confusion.

Here's an example of where new scope doesn't make sense in my opinion:

ui.directive('box', function() {
    return {
        restrict: 'E',
        transclude: true,
        template: '<div ng-transclude/>',
        replace: true,
        scope: {}
    };
});

All this directive wants is replace the <box>content</box> with a <div>content</div> and the content to have the isolated scope.

Creating nested structure of directives like this leads to a scope tree pollution. Here's a plunker example (http://plnkr.co/edit/DwukVGGprFFjQuVY8yTz) of three nested directives which create a scope tree structure like this:

< Scope (002) : ng-app
    < Scope (003) : ng-controller
        < Scope (004) : box
        < Scope (005) : ng-transclude
            < Scope (006) : box
            < Scope (007) : ng-transclude
                < Scope (008) : box
                < Scope (009) : ng-transclude

This behaviour doesn't seem to add any value to its purpose but creates a lot of confusion among beginners.

At the moment I use the following workaround which achieves exactly what the previous example does:

ui.directive('box', function() {
    return {
        restrict: 'E',
        transclude: true,
        template: '<div/>',
        replace: true,
        scope: {},
        link: function(scope, element, attrs, transclude) {
            transclude(scope.$parent, function(content) {
                element.append(content);
            });
        }
    };
});

Here's a plunker example (http://plnkr.co/edit/46v6IBLkhS71L1WbUDFl) which illustrates this concept. It leaves the scope tree nice and tidy:

< Scope (002) : ng-app
    < Scope (003) : ng-controller
        < Scope (004) : box
        < Scope (005) : box
        < Scope (006) : box

And the 2-way binding works the way many expect when they bind 'value' rather than 'object.value'. (I believe that the fact that passing just 'value' works in some cases but not the other and blaming the nature of prototypal inheritance in javascript is not a good excuse. The fact that many people find this behaviour unexpected indicates that there's an architectural flaw.)

I would love to hear what other people think and use cases where they think that creating a new sibling scope for ng-transclude makes sense.

mbykovskyy avatar Dec 20 '13 00:12 mbykovskyy

+1

alan-morey avatar Feb 27 '14 21:02 alan-morey

+1

blackgate avatar Mar 18 '14 18:03 blackgate

+1

mhtsbt avatar Mar 28 '14 10:03 mhtsbt

+1

guilleferrer avatar Apr 16 '14 09:04 guilleferrer

@caitp

Or, if you wanted to be super fancy, perhaps you could avoid breaking changes entirely by allowing ngTransclude to specify that it wants a new scope or not, via the attribute value.

Whatever doesn't have breaking changes gets my vote.

boneskull avatar Apr 23 '14 07:04 boneskull

+1

paulpflug avatar May 02 '14 08:05 paulpflug

+1

ravishivt avatar May 26 '14 22:05 ravishivt

+1

c0bra avatar Jun 04 '14 15:06 c0bra

+1

nickholub avatar Jun 14 '14 01:06 nickholub

+1

awashbrook avatar Jun 30 '14 05:06 awashbrook

Related: https://github.com/angular/angular.js/issues/7874

Izhaki avatar Jul 01 '14 15:07 Izhaki

+1. I always wondered about this behavior. I like this solution from caitp:

@caitp

Or, if you wanted to be super fancy, perhaps you could avoid breaking changes entirely by allowing > ngTransclude to specify that it wants a new scope or not, via the attribute value.

jibwa avatar Jul 17 '14 04:07 jibwa

+1

nahn avatar Jul 22 '14 09:07 nahn

+1

Boux avatar Jul 23 '14 18:07 Boux

+1

plumpNation avatar Jul 29 '14 13:07 plumpNation

For those watching this issue, I've created an 'improved' ng-transclude directive, the attribute value of which defines the internal scope sought after and can be one of 3:

  • silbing - The transcluded contents scope is a sibling one to the element where transclusion happens. That's the current ng-transclude behaviour.
  • parent - The transcluded contents scope is that of the element where transclusion happens.
  • child - The transcluded contents scope is child scope to the scope of the element where transclusion happens.

Example usage:

template: 
  '<div ng-transclude="parent">' +
  '</div>'

Full example

See this plunk for an example of all.

The output looks like so:

image

Source

.config(function($provide){
    $provide.decorator('ngTranscludeDirective', ['$delegate', function($delegate) {
        // Remove the original directive
        $delegate.shift();
        return $delegate;
    }]);
})

.directive( 'ngTransclude', function() {
  return {
    restrict: 'EAC',
    link: function( $scope, $element, $attrs, controller, $transclude ) {
      if (!$transclude) {
        throw minErr('ngTransclude')('orphan',
         'Illegal use of ngTransclude directive in the template! ' +
         'No parent directive that requires a transclusion found. ' +
         'Element: {0}',
         startingTag($element));
      }

      var iScopeType = $attrs['ngTransclude'] || 'sibling';

      switch ( iScopeType ) {
        case 'sibling':
          $transclude( function( clone ) {
            $element.empty();
            $element.append( clone );
          });
          break;
        case 'parent':
          $transclude( $scope, function( clone ) {
            $element.empty();
            $element.append( clone );
          });
          break;
        case 'child':
          var iChildScope = $scope.$new();
          $transclude( iChildScope, function( clone ) {
            $element.empty();
            $element.append( clone );
            $element.on( '$destroy', function() {
              iChildScope.$destroy();
            });            
          });
          break;
      }
    }
  }
})

Izhaki avatar Aug 26 '14 16:08 Izhaki

As the issue I raised earlier in #8609 was closed as an duplicate of this thread, I'm restating it here.

In my opinion the current way a scope is created for the transcluded part of the DOM is highly illogical! It goes against the normal flow in angular, and should be fixed!

Here is an extract of my previous issue:

I created a small plunk to illustrate my issue here.

the prime offender is in this directive

     function pane() {
        return {
           restrict: 'E',
           transclude: true,
           scope: {
              title: '@'
           },
           template: '<div style="border: 1px solid black;">' +
              '<div style="background-color: gray">{{title}} (isolate scope id: {{$id}})</div>' +
              '<ng-transclude></ng-transclude>' +
              '</div>'
        };
     }

When a user does something like this:

<form>
    <pane title='enter your name'>
         <input type='text ngModel='username'>
    </pane>
    <pane title='enter your token'>
         <input type='text ngModel='token'>
   </pane>
The result will be surprising to many, especially new users. And this is even a (overly) simplified use case. Try putting in the display of some validation messages there;)

This is a different use case as where this issue started with, but I agree that it is basicly the same issue!

It makes way more sense to transclude the scope with the dom element instead. If a new scope is really needed a user can put an ngController on the ngTransclude element anyway. Or there can be an optional flag on ngTransclude that triggers one. That flag can be used to solve the #5489 use case too. And it can be used for the solution caitp offered too.

SanderElias avatar Sep 02 '14 16:09 SanderElias

+1

xantorres avatar Sep 28 '14 11:09 xantorres

+1

joehannes-zz avatar Sep 29 '14 05:09 joehannes-zz

+1

fredericlefeurmou avatar Oct 09 '14 21:10 fredericlefeurmou