AngularJS - 从 transclude 范围访问指令范围 [英] AngularJS - access directive scope from transclude scope

查看:25
本文介绍了AngularJS - 从 transclude 范围访问指令范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有某种形式的指令.通常这就是我所需要的,但有时我需要添加更多的输入字段.所以我尝试为此使用嵌入,但它不起作用.

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.

我创建了一个 plunker 来说明: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 - 从 transclude 范围访问指令范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆