I have a setup like this:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function() {});
myApp.directive("grandParent", function() {
return {
template: [
'<div style="border: 1px solid">',
'<p>transcluded view is below:</p>',
'<ng-transclude></ng-transclude>',
'</div>'
].join(""),
transclude: true,
controller: function() {
this.getMe = "grandParentCtrl.controller.getMe";
}
};
});
myApp.directive('parent', function($compile) {
return {
require: "^^grandParent",
link: function($scope, $element, $attrs, grandParentCtrl) {
$element.append($compile('<son></son>')($scope, undefined, {
transcludeControllers: {
grandParent: {
instance: grandParentCtrl
}
}
}));
}
}
});
myApp.directive('son', function($compile) {
return {
require: '^^grandParent',
template: [
'<div class="btn btn-danger">',
'abc: <i>{{abc}}</i>',
'</div>'
].join(""),
link: function(scope, element, attrs, ctrl) {
scope.abc = ctrl.getMe;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl as vm">
<grand-parent>
<parent></parent>
</grand-parent>
</div>
(grand-parent
directive has parent
directive. The parent
directive $compile
s son
directive)
In the directive son, if I require: "^^grandParent"
it gives an error saying
"grandParent" directive required by "son" directive cannot be found
BUT, if in son I write require: "^grandParent"
(*using ^ instead of ^^) it works.
If we look at the resulting HTML, it looks like this:
<grand-parent>
<parent>
<son>
</son>
</parent>
</grand-parent>
Obviously, grand-parent is strictly an ancestor of son. So why the error?