问题描述
我有某种形式的指令.通常,这就是我所需要的,但有时我需要添加一些其他输入字段.因此,我尝试为此使用转写,但这是行不通的.
I have a directive with some form. Usually it is all I need, but sometimes I need to add some more input fields. So I tried to use transclusion for that, but it doesn't work.
我创建了一个监听器来说明: http://plnkr.co/edit/zNOK3SJFXE1PxsvUvPBQ? p =预览
I created a plunker to ilustrate that: http://plnkr.co/edit/zNOK3SJFXE1PxsvUvPBQ?p=preview
指令是一种简单的表单,具有输入字段,包含和一个按钮,可用于对其进行测试(并非省略了重要部分):
Directive is a simple form with input field, transclusion and a button to help testing it (not important parts ommitted):
scope: {
},
transclude: 'element',
template:
'<form name="myForm">' +
'<input type="text" ng-model="data.inDirective"></input>' +
'<div ng-transclude></div>' +
'<button ng-click="showData()">show data</button>' +
'</form>'
在这里它与包含一起使用:
And here it is used with transclusion:
<form-as-directive>
<input type="text" ng-model="data.inTransclude"></input>
</form-as-directive>
我可以在转换中以某种方式使用指令的作用域吗?
Can I somehow use directive's scope in the transclusion?
推荐答案
如果您需要将包含在html中的控件绑定到指令的(隔离)范围,则必须手动"执行包含(不包含ng -transclude),则使用链接函数的transcludeFn参数.此功能使您可以更改包含范围.
If you need to bind the controls in the transcluded html to the (isolate) scope of the directive, you have to do the transclusion "manually" (without ng-transclude), using the transcludeFn parameter of the link function. This function allows you to change the scope of the transclusion.
scope: {
},
transclude: 'element',
replace: true,
template:
'<form name="myForm">' +
'<input type="text" ng-model="data.inDirective"></input>' +
'<div class="fields"></div>' +
'<button ng-click="showData()">show data</button>' +
'</form>',
link: function (scope, elem, attrs, ctrl, transcludeFn) {
// "scope" here is the directive's isolate scope
elem.find('.fields').append(transcludeFn(scope, function () {}));
}
否则,将包含项自动绑定到父(控制器)作用域的(新)子级,以便能够(通过继承)访问该父作用域的属性.
Otherwise, the transclusion is automatically bound to a (new) child of the parent (controller) scope, in order to have access to the properties of that parent scope (through inheritance).
这篇关于AngularJS-超越范围的访问指令范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!