Angularjs directive uses transclude attribute

使用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
2
3
4
5
<div>
<button-group>
<button>Enter</button>
</button-group>
</div>

透過ng-transclude,將原先在button-group裡的child-element添加至ng-transclude裡面:

1
2
3
4
5
6
7
8
9
10
11
app.directive( "buttonGroup", function(){

return {

restrict: 'EA',
template: '<div class="btn-group" ng-transclude ></div>',
replace: true,
transclude: true
};

});

最後就會取得到底下的結果:

1
2
3
4
5
<div>
<div class="btn-group" ng-transclude="">
<button class="ng-scope">Enter</button>
</div>
</div>

透過directive的controller添加child element

使用$transclude取得clone的element,在append至需要添加的地方:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
controller: ['$scope', '$element', '$transclude', function ($scope, $element, $transclude) {

$transclude(function(clone) {

var primaryBlock = $element.find('div.primary-block');
var transcludedButtons = clone.filter(':button');

angular.forEach(transcludedButtons, function(e) {

if (angular.element(e).hasClass('primary')) {
primaryBlock.append(e);
}

});
});
}]

使用ngTransclude的Demo

完整的範例,請參考jsfiddle上的code。