有谁知道为什么如果我试图在 Controller 中直接获取父级,我会得到 undefined
?如果我在函数内部使用它,效果很好。
var sidebar = {
transclude: true,
bindings: {
isOpen: '='
},
controller: function () {
function toggle() {
//this.isOpen = !this.isOpen;
console.log('my test');
}
this.toggle = toggle;
},
template: ['$element', '$attrs',function ($element, $attrs) {
return [
'<div class="sidebars" ng-transclude>',
'</div>'
].join('');
}]
};
var sidebarItem = {
require: {
parent: '^sidebar'
},
bindings: {
header: '='
},
controller: function () {
function mytest() {
// this works
console.log('isOpen is ',this.parent.isOpen);
this.parent.toggle();
}
// here I got Parent is undefined
console.log('Parent is ',this.parent);
//this.parent.toggle();
this.mytest = mytest;
},
template: ['$element', '$attrs',function ($element, $attrs) {
return [
'<div class="sidebar__item">',
'<h3 ng-click="$ctrl.mytest();">{{$ctrl.header}}</span>',
'<ul>',
'<li>Test</li>',
'</ul>',
'</div>'
].join('');
}]
};
angular.module('layout.directives', [])
.component('sidebar', sidebar)
.component('sidebarItem', sidebarItem);
最佳答案
如果你换行
console.log('Parent is ',this.parent);
有了$timeout
,问题就解决了。
所以,像这样:
$timeout(function(){
// here I got Parent is undefined
console.log('Parent is ',this.parent);
})
required
组件的 Controller 似乎只有在摘要循环完成后才可用。这就是它在从模板(在 mytest()
函数中)调用时起作用的原因。
关于angularjs - Angular 嵌套组件父级未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37341080/