AngularJS - 从transclude scope访问指令scope

6
我有一个带有一些表单的指令。通常这就是我需要的,但有时我需要添加更多的输入字段。因此,我尝试使用插入来实现,但它不起作用。
我创建了一个plunker来说明这一点:http://plnkr.co/edit/zNOK3SJFXE1PxsvUvPBQ?p=preview 该指令是一个简单的表单,包含输入字段、插入和一个按钮来帮助测试它(省略了不重要的部分)。
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>'

这里是使用 transclusion 的示例:

<form-as-directive>
  <input type="text" ng-model="data.inTransclude"></input>
</form-as-directive>

我能否在插槽中使用指令的作用域(scope)?

2个回答

7

如果你需要将传递的html中的控件绑定到指令的(隔离)作用域中,你需要“手动”进行传递(不使用ng-transclude),并利用link函数的transcludeFn参数。这个函数允许你改变传递的作用域。

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 () {}));
}

否则,插入操作会自动绑定到父(控制器)作用域的一个(新的)子级,以便可以通过继承访问该父作用域的属性。

1
似乎你需要的是$$nextSibling
 scope.$$nextSibling.data.inTransclude

来自这里

当存在一个插入的作用域和一个隔离的作用域时,隔离作用域属性 $$nextSibling 将引用插入作用域。

Plunk:http://plnkr.co/edit/z2Bmfx?p=preview


1
这个答案已经过时了。在1.3版本之后,隔离作用域是被转移作用域的$parent。 - Arashsoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接