我的复合组件(多个嵌入指令)的实现基于以下思想:
- 使用一个指令捕获子组件 $transclude
- 用另一个指令输出这个子组件
现场演示http://nickholub.github.io/angular-composite-component/#/
演示源代码https://github.com/nickholub/angular-composite-component
指令源代码https://github.com/nickholub/angular-composite-component/blob/master/app/directive/angular-composite-component.js
<div cs-composite>
<div cs-section="header">
Composite Component Header
</div>
<div cs-section="footer">
Composite Component Footer
<div>Random Value: {{randomValue}}</div>
<div>Percentage: {{percentage}}%</div>
</div>
</div>
捕获内容的指令
.directive('csSection', function () {
return {
transclude: 'element',
priority: 100,
require: '^csComposite',
link: function (scope, element, attrs, ctrl, $transclude) {
var directiveTransclude = {
id: attrs.csSection,
transclude: $transclude,
element: element
};
ctrl.registerTransclude(directiveTransclude);
}
};
})
输出内容的指令
.directive('csTransclude', function () {
return {
transclude: true,
link: function (scope, element, attrs) {
var id = attrs.csTransclude;
var directiveTransclude = scope.transcludes[id];
if (directiveTransclude) {
var selectedScope = scope.$new();
directiveTransclude.transclude(selectedScope, function (clone) {
element.append(clone);
});
}
}
};
})