我有一个不同的答案,这不是黑客,我希望它会被接受..
查看我的 plunkr进行现场演示
这是我对该指令的使用
<div custom-directive custom-name="{{name}}">
if transclude works fine you should see my name right here.. [{{customName}}]
</div>
请注意,我customName
在指令中使用,并为其分配了一个值作为指令范围的一部分。
这是我的指令定义
angular.module('guy').directive('customDirective', function($compile, $timeout){
return {
template : '<div class="custom-template">This is custom template with [{{customName}}]. below should be appended content with binding to isolated scope using the transclude function.. wait 2 seconds to see that binding works</div>',
restrict: 'AC',
transclude: true,
scope : {
customName : '@'
},
link : function postLink( scope, element, attrs, dummy, transcludeFn ){
transcludeFn( scope, function(clone, innerScope ){
var compiled = $compile(clone)(scope);
element.append(compiled);
});
$timeout( function(){
scope.customName = 'this stuff works!!!';
}, 2000);
}
}
});
请注意,我将在 2 秒后更改范围上的值,以便显示绑定有效。
在网上看了很多之后,我明白了以下几点:
- ng-transclude 指令是嵌入的默认实现,用户可以根据用例重新定义
- 重新定义一个嵌入意味着 Angular 将在每个上使用您的定义
$digest
- 默认情况下 - 嵌入会创建一个新范围,它不是孤立范围的子范围,而是兄弟范围(因此 hack 起作用)。如果您重新定义嵌入过程,您可以选择在编译嵌入内容时使用哪个范围.. - 即使仍然创建了一个新范围,它似乎
- transclude 函数没有足够的文档。我什至没有在文档中找到它。我在另一个 SO 答案中找到了它