AngularJS - access directive scope from transclude

2019-06-26 05:10发布

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?

2条回答
三岁会撩人
2楼-- · 2019-06-26 05:50

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

查看更多
趁早两清
3楼-- · 2019-06-26 05:50

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

查看更多
登录 后发表回答