如果您希望将控制器的范围绑定到您传入的HTML,则使用transclude on指令非常有用。
你将如何完成相反的操作? (可以从控制器中访问指令的范围)
这是我想要实现的一个例子:
<my-directive model='controllerModel'>
{{directiveModel}}
</my-directive>
.directive(function () {
return {
transclude: true,
template: '<div ng-transclude></div>'
scope: {
directiveModel: '=model'
}
}
})
在此示例中,可以从“transcluded”的HTML中访问scope属性“directiveModel”。
当然,这不起作用,因为控制器的范围与传入的HTML绑定。
我不确定如何以最佳方式实现此目的(可以从控制器内访问指令的范围)。
我能想到的最好的方法是不使用transclude,而是使用.html()将HTML注入模板,然后使用$ interpolate服务将指令范围绑定到HTML。
问题在于,如果为指令定义模板,angular将在您访问指令之前用指令HTML替换您“传入”的HTML。
答案 0 :(得分:3)
如果要在transcluded内容中访问directiveModel,可以使用transclude函数手动执行转换过程,而不是使用ng-transclude。使用transclude函数时,可以更改要使用的范围。
app.directive('myDirective', function(){
return {
restrict: 'E',
transclude: true,
template: '<div></div>',
scope: {
directiveModel: '=model'
},
link: function(scope, element, attrs, ctrl, transcludeFn){
transcludeFn(scope, function(clonedTranscludedContent ) {
element.append(clonedTranscludedContent);
});
}
}
});