代码的简化示例....
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');
那么世界上一切都很好......如果另一个人需要控制器,如何访问父控制器中的被抄送内容?
答案 0 :(得分:0)
我弄清楚这是什么回事......如果你以这种方式使用$transclude
,你必须记住手动附加被抄送的内容。所以...
$transclude(clone => {
// do something then...
$element.append(clone);
}, null, 'slide');