3

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);
2
  • AFAIK, you access in angular to the parent scope through your own scope, so instead of this.parent, I'd access with this.$scope.$parent Commented May 20, 2016 at 8:17
  • I believe this is to do with the subtle differences between $scope and this. See this question stackoverflow.com/questions/11605917/… plus the fact that you're actually referring to this.parent in the function Commented May 20, 2016 at 8:30

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.