Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular nested component parent is undefined

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);
like image 574
Whisher Avatar asked Jul 28 '26 09:07

Whisher


1 Answers

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).

like image 112
Nahn Avatar answered Jul 30 '26 08:07

Nahn