Angularjs: transclude directive template

前端 未结 3 821
忘掉有多难
忘掉有多难 2020-12-09 06:07

How to use transclusion in the below case. The intention is to use markup in the html (partials) file, than defining it in template (within the directive).

I found a

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 06:43

    Very very late to the party. I needed this for a project so after dwelling into it and finding other great approaches and directions, finally came up with this:

    Same code as the ng-transclude directive, but with small addition of context binding that the directive watch and sets on the transcluded generated scope each time it changes. Same as ng-repeat does, but this allows:

    1. using the customize ng-transclude with ng-repeat without the hassle of rewriting ng-repeat and like angular/2 template outlet.
    2. Having the transcluded content keep access the grandparent scope while receiving direct context data from the parent. Same as template outlet again.

    The augmented ng-transclude function:

    return function ngTranscludePostLink(
       ...
      ) {
      let context = null;
      let childScope = null;
      ...
      $scope.$watch($attrs.context, (newVal, oldVal) => {
        context = newVal;
        updateScope(childScope, context);
      });
      ...
      $transclude(ngTranscludeCloneAttachFn, null, slotName);
      ...
      function ngTranscludeCloneAttachFn(clone, transcludedScope) {
         ...                                 
         $element.append(clone);
         childScope = transcludedScope;
         updateScope(childScope, context);
         ...
      }
      ...
      function updateScope(scope, varsHash) {
        if (!scope || !varsHash) {
          return;
        }
        angular.extend(scope, varsHash);
      }
    }
    

    And it's usage:

    App

    
       
    App data: {{ $ctrl.header }}
    Name:{{ name }} Year: {{ year }} Rating: {{ rating }}

    MyList

    • Ng repeat item scope id: {{ $id }}

    Full directive code can be found here on GitHub

提交回复
热议问题