Does anyone know why if I try to get the parent straight in the controller I get undefined? If I use it inside a function it works nice.
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);
If you wrap
console.log('Parent is ',this.parent);
with a $timeout, problem solved.
So, like this:
$timeout(function(){
// here I got Parent is undefined
console.log('Parent is ',this.parent);
})
It seems that the required component's controller is only available after digest cycle has completed. That's why it works when it is called from the template (in the mytest() function).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With