AngularJS - dynamically generated directive "requires" doesn't work
The "require" parameter does not work if the directive is dynamically created, so it cannot reference its parent's controllers. How can I get it to work?
app.directive('parent', function ($compile) {
return {
controller: function() {},
link: function (scope, el, attrs) {
// "child" is dynamically created
el.append( $compile('<div child>')(scope) );
}
}
})
.directive('child', function () {
return {
require: "?^parent",
link: function(scope, el, attrs, pCtrl) {
// "child" cannot find its parent controller
console.log("pCtrl is undefined: ", pCtrl);
}
}
})
here plunker DEMO
+3
source to share
1 answer
you need to add a child to the parent before compiling it.
When the directive compiles, it tries to get its parent. And from the parent element, it tries to find the parent controller. But you are compiling your child directive before you add its element to your parent.
I created plnkr for you. Checkout this
app.directive('parent1', function($compile, $timeout) {
return {
controller: function() {
this.name = 'parent controller 1';
},
link: function(scope, el, attrs) {
// "child1" is dynamically created
var elmChild = angular.element('<div child1>');
el.append(elmChild);
$compile(elmChild)(scope);
}
}
})
+7
source to share