gfa*_*ess 3 directive angularjs
如果指令是动态创建的,则"require"选项不起作用,因此它不能引用其父项的控制器.我怎样才能使它工作?
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);
}
}
})
Run Code Online (Sandbox Code Playgroud)
这是一个吸血鬼的DEMO
你需要在编译之前将子元素添加到父元素.
当指令编译时,它试图获取其父元素.从父元素,它试图找到父控制器.但是,在将其元素附加到其父元素之前,您正在编译子指令.
我为你创造了一个plnkr.结帐这个
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);
}
}
})
Run Code Online (Sandbox Code Playgroud)