AngularJS - access directive scope from transclude scope

孤街醉人 提交于 2019-12-12 11:17:39

问题


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.

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?


回答1:


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).




回答2:


Seems like $$nextSibling is what you need :

 scope.$$nextSibling.data.inTransclude

From here :

When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope.

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



来源:https://stackoverflow.com/questions/19301692/angularjs-access-directive-scope-from-transclude-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!