使用directive時,會將符合restrict的element都做初始化,directive指向的element包含child-element,這時候就要設定transclude:true
,將child-element,添加到template裡,可以使用ng-transclude或者透過directive定義controller去處理。
透過ng-transclude處裡child element
定義好tag的結構,button-group
為預設tag:
1 | <div> |
透過ng-transclude
,將原先在button-group
裡的child-element添加至ng-transclude
裡面:
1 | app.directive( "buttonGroup", function(){ |
最後就會取得到底下的結果:
1 | <div> |
透過directive的controller添加child element
使用$transclude
取得clone的element,在append
至需要添加的地方:
1 | controller: ['$scope', '$element', '$transclude', function ($scope, $element, $transclude) { |
使用ngTransclude的Demo
完整的範例,請參考jsfiddle上的code。