$ctrl对象在transcluded作用域中不可用

$ctrl object not available in transcluded scope?

本文关键字:作用域 transcluded ctrl 对象      更新时间:2023-09-26

使用ng-transclude时,我无法访问新angular.component()$ctrl作用域绑定。

我想访问$ctrl而不是页面上的.controller(),因为我们希望迁移到angular2而不是轨道。

这里有一个演示者:https://plnkr.co/edit/M4k7Av8Q2OrMSsvhZjsb?p=preview

希望有人能给我们一些启示!以下代码:

// app.js
angular.module('test.app', [])
.component('transcludedComponent', {
  transclude: true,
  template: '<div ng-transclude></div>',
  controller: function(){
    this.text = 'hello world'
  }
})
.component('regularComponent', {
  template: '<h2>{{$ctrl.otherText}}</h2>',
  controller: function(){
    this.otherText = 'this binding works';
  }
});
angular.element(document.body).ready(function(){
    angular.bootstrap(document, ['test.app']);
});
<!-- index.html -->
<transcluded-component>
  <h2>transcluded text has no $ctrl: {{ $ctrl.text }}</h2>
  <regular-component></regular-component>
</transcluded-component>

任何有同样问题的人,我只是用$parent代替$ctrl来访问正确的作用域。虽然很糟糕,但它很管用。