在所需控制器中使用$ transclude时,找不到所需的控制器

时间:2016-03-04 12:33:09

标签: angularjs angularjs-ng-transclude

代码的简化示例....

HTML:

<div ng-app="app">
  <m-carousel>
    <m-carousel-slide>foo</m-carousel-slide>
    <m-carousel-slide>bar</m-carousel-slide>
  </m-carousel>
</div>

JavaScript的:

class CarouselDirectiveController {
  constructor($transclude) {
    $transclude(clone => {
      // do something
    }, null, 'slide');
  }
}

class CarouselSlideDirectiveController {
  $onInit() {
    console.log(this.carousel);
  }
}

function carouselDirective() {
  return {
    restrict: 'E',
    replace: true,
    controller: CarouselDirectiveController,
    controllerAs: 'carousel',
    template: '<div class="m-carousel" ng-transclude="slide"></div>',
    transclude: {
      slide: 'mCarouselSlide'
    },
    scope: {},
    bindToController: true
  };
}

function carouselSlideDirective() {
  return {
    restrict: 'E',
    replace: true,
    transclude: true,
    controller: CarouselSlideDirectiveController,
    controllerAs: 'carouselSlide',
    template: '<div class="m-carousel-slide" ng-transclude></div>',
    scope: {},
    bindToController: true,
    require: {
      carousel: '^^mCarousel'
    }
  };
}

angular.module('app.carousel', [])
  .directive('mCarousel', carouselDirective)
  .directive('mCarouselSlide', carouselSlideDirective);

angular.module('app', ['app.carousel']);

这会引发以下错误:

https://docs.angularjs.org/error/ $编译/ ctreq P0 = mCarousel&安培; P1 = mCarouselSlide

但是,如果我注释掉$transclude(clone => {}, null, 'slide');那么世界上一切都很好......如果另一个人需要控制器,如何访问父控制器中的被抄送内容?

CodePen:http://codepen.io/anon/pen/KzdNRE?editors=1011

1 个答案:

答案 0 :(得分:0)

我弄清楚这是什么回事......如果你以这种方式使用$transclude,你必须记住手动附加被抄送的内容。所以...

$transclude(clone => { 
  // do something then... 
  $element.append(clone); 
}, null, 'slide');