"要求"如果指令是动态创建的,则选项不起作用,因此它不能引用其父项'控制器。我怎样才能使它发挥作用?
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);
}
}
})
这是一个plunker DEMO
答案 0 :(得分:7)
您需要在编译之前将子元素添加到父元素。
当指令编译时,它会尝试获取其父元素。从父元素,它试图找到父控制器。但是,在将其元素附加到其父元素之前,您正在编译子指令。
我为你创造了一个plnkr。结帐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);
}
}
})