During my experimentation with transclusion, I wanted to test whether the transcluded directive could successfully locate its required parent directive controller after being transcluded under it. The directives used in this experiment are as follows: - There is a ParentOfParent directive with transclude:true. - A Parent directive embedded within the ParentOfParent directive template. - A Child directive which requires the Parent controller and is transcluded by ParentOfParent to become a child of the Parent directive.
'use strict';
angular
.module('angularlabApp', [
'ngRoute',
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
});
'use strict';
angular.module('angularlabApp')
.directive('parent', function () {
return {
controller: function () { },
restrict: 'EA',
link: function postLink(scope, element, attrs) {
console.log('Parent Link');
}
};
});
'use strict';
angular.module('angularlabApp')
.directive('parentOfParent', function () {
return {
template: '<div id="prnt" parent></div>',
transclude: true,
restrict: 'EA',
link: function(scope, element, attrs,_,transcludeFn){
console.log('POP Link');
element.find('#prnt').append(transcludeFn());
}
};
});
'use strict';
angular.module('angularlabApp')
.directive('child', function () {
return {
template: '<div></div>',
restrict: 'EA',
require:'^parent',
link: function postLink(scope, element, attrs) {
console.log('Child Link');
}
};
});
'use strict';
angular.module('angularlabApp')
.controller('MainCtrl', function ($scope) {
});
While conducting the tests, I noticed an interesting discrepancy when using the transclusion function with and without cloning. When I use the transclusion function output without passing the cloneFn, an error occurs stating that the child directive cannot find the Parent Controller above it. [http://plnkr.co/edit/JteQpPMc6nbVNjRDHVZ2](http://plnkr.co/edit/JteQpPMc6nbVNjRDHVZ2)
However, everything works smoothly when I pass the cloneFn while using it.
This raised the question for me - is it feasible for a transcluded directive to discover the required controller after being inserted below the directive it belongs to?