2

I am trying to console.log myobject but I keep getting undefined. I tried using $scope.watch and $attrs.$observe. Can someone tell me what I'm doing wrong.

here is the html

<my-component some-data="$ctrl.data"></my-component>

here is the component and controller

module.component('myComponent', {
bindings: {
  needThisStuff: '<someData'
},
controller: Ctrl,
templateUrl:
  requirejs.toUrl('path/to/templ.html')
 });

function Ctrl(){
var self = this;
console.log(self.needThisStuff);
}

how can I access needThisStuff using $watch or $observe or anything else, I am using angular 1.5

4
  • Show how you set $ctrl.data, this is probably the issue. Component code is correct. Commented Jun 23, 2016 at 20:37
  • $ctrl.data is a object inside another components controller Commented Jun 23, 2016 at 20:57
  • if I pass to the binding data=$ctrl I can console.log(self.data) and see the entire $ctrl object but when I do data=$ctrl.data it gives undefined. Commented Jun 23, 2016 at 21:02
  • And one more time: show how you set $ctrl.data. Commented Jun 23, 2016 at 21:03

1 Answer 1

2

I'm pretty sure the object is undefined because your console.log fires as soon as the component loads. The data hasn't been returned yet, so it is still undefined.

As a basic way to test this, you could wrap your console.log in a $timeout just to test.

To fix this, use angular component lifecycle hooks. Change your Ctrl to be something like this:

function Ctrl {
    var self = this;
    this.$onChanges = function(changesObj) {
       console.log(changesObj.needThisStuff);
    }
}

$onChanges is called whenever one-way bindings are updated, which in this case is your needThisStuff variable.

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.