3

i'm currently trying to figure out why my directive or my component behave different when using transclude: true.

Navigation.hbs

<my-custom-element ng-transclude>
  <div>
    <h3>Scope: {[{$ctrl.test}]}</h3>
  </div>
</my-custom-element>

Directive

function CustomDirective() {
  return {
   restrict: 'E',
   replace: true,
   controller: MyController,
   controllerAs: '$ctrl',
   transclude: true
  }
}

export function register(ngModule) {
  ngModule.directive('myCustomElement', CustomDirective);
}

Component

const CustomComponent = {
  controller: MyController,
  transclude: true,
  replace: true,
};

export function register(ngModule) {
  ngModule.component('myCustomElement', CustomComponent);
}

Controller

export default class MyController {
  constructor() {
    this.test = 'this is just a teststring';
  }
}

Explanation I've got server-side rendered handlebars templates. On the client side, I want to add some logic to my view. The idea is to take the existing view and bind a component to it, so that I can inject a controller.

My problem is, when I'm using the directive-based approach, the existing view gets transcluded, and {[{$ctrl.test}]} gets replaced with this is just a teststring. Using the component-based approach {[{$ctrl.test}]} is not replaced, as if controller wasn't bound.

I'Ve read a lot about using the link function for managing scopes when transcluding, but I don't want to use a directive, and components do not have the link function.

Does anyone know what I'm missing? Maybe it's nothing, but after hours of googling, I could not find any helpful resources. Maybe I'm just googling the wrong thing.

amanuel2
  • 4,508
  • 4
  • 36
  • 67

1 Answers1

0

You may try to use $parent to get access to component controller from transcluded part. In order to do so you should add <ng-transclude></ng-transclude> slot into your custom element template, something like:

Component

const CustomComponent = {
    controller: MyController,
    transclude: true,
    template: '<ng-transclude></ng-transclude>'
};

export function register(ngModule) {
    ngModule.component('myCustomElement', CustomComponent);
}

Navigation.hbs

<my-custom-element>
    <div>
        <h3>Scope: {[{ $parent.$ctrl.test }]}</h3>
    </div>
</my-custom-element>

Please note that replace: true is deprecated.