我有一个表格的指令.通常它只是我需要的,但有时我需要添加更多的输入字段.所以我尝试使用transclusion,但它不起作用.
我创造了一个用来说明这一点的掠夺者:http://plnkr.co/edit/zNOK3SJFXE1PxsvUvPBQ?p=preview
Directive是一个简单的表单,带有输入字段,transclusion和一个帮助测试它的按钮(不包括重要部分):
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>'
在这里,它与翻译一起使用:
<form-as-directive> <input type="text" ng-model="data.inTransclude"></input> </form-as-directive>
我可以以某种方式在转换中使用指令的范围吗?
解决方法
如果需要将transcluded html中的控件绑定到指令的(isolate)范围,则必须使用link函数的transcludeFn参数“手动”(不使用ng-transclude)进行转换.此功能允许您更改转换的范围.
scope: { },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 () {})); }