AngularJS-动态创建的指令';s";要求;不起作用
如果指令是动态创建的,“require”选项不起作用,因此它不能引用其父控制器。我怎样才能让它工作AngularJS-动态创建的指令';s";要求;不起作用,angularjs,directive,Angularjs,Directive,如果指令是动态创建的,“require”选项不起作用,因此它不能引用其父控制器。我怎样才能让它工作 app.directive('parent', function ($compile) { return { controller: function() {}, link: function (scope, el, attrs) { // "child" is dynamically created el.append( $compile('<d
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);
}
}
})
app.directive('parent',function($compile){
返回{
控制器:函数(){},
链接:功能(范围、el、属性){
//“子”是动态创建的
el.追加($compile(“”)(范围));
}
}
})
.指令('child',函数(){
返回{
要求:“^parent”,
链接:功能(范围、el、属性、pCtrl){
//“子”找不到其父控制器
log(“pCtrl未定义:”,pCtrl);
}
}
})
这里有一个在编译之前,您需要将子元素添加到父元素中 当指令编译时,它会尝试获取其父元素。并从父元素中尝试查找父控制器。但是,在将子指令的元素附加到其父元素之前,您正在编译子指令 我已经为你创建了一个plnkr。结帐
app.directive('parent1',函数($compile,$timeout){
返回{
控制器:函数(){
this.name='父控制器1';
},
链接:功能(范围、el、属性){
//“child1”是动态创建的
var elmChild=angular.element(“”);
el.append(elmChild);
$compile(elmChild)(范围);
}
}
})
这里也有同样的问题。我运行$compile,然后追加。没有意识到订单会影响所需的属性。
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);
}
}
})