Angular 1.5组件与指令ng-transclude

时间:2016-03-10 23:29:52

标签: angularjs handlebars.js angularjs-ng-transclude

我正在尝试弄清楚为什么我的指令或我的组件在使用transclude时表现不同:true。

Navigation.hbs

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

指令

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

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

组件

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

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

控制器

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

解释 我有服务器端渲染的把手模板。在客户端,我想在我的视图中添加一些逻辑。我们的想法是获取现有视图并将组件绑定到它,以便我可以注入一个控制器。

我的问题是,当我使用基于指令的方法时,现有视图会被转换, {[{$ ctrl.test}]} 会被取代只是一个测试字符串。 使用基于组件的方法 {[{$ ctrl.test}]} 不会被替换,就像控制器没有绑定一样。

我已经阅读了很多关于在转换时使用链接函数来管理作用域的内容,但是我不想使用指令,并且组件没有链接函数。

有谁知道我错过了什么?也许没什么,但经过几个小时的谷歌搜索,我找不到任何有用的资源。 也许我只是在谷歌搜索错误的东西。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用$parent从转换部分访问组件控制器。为此,您应该将<ng-transclude></ng-transclude>插槽添加到自定义元素模板中,例如:

<强>组件

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>

请注意replace: true is deprecated