Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - access directive scope from transclude scope

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?

like image 312
amorfis Avatar asked Oct 10 '13 16:10

amorfis


1 Answers

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

like image 151
cipak Avatar answered Dec 15 '22 21:12

cipak