Question

Why am I able to see a property inside my scope printed with console.log(), but directly afterwards when I try to access it it's undefined?

The following code is inside a directive's controller function:

console.log($scope); //a scope object with a defined "output" property
console.log($scope.output); //undefined

Here is the output of my scope from the first console.log().

Scope {$id: "008", $$childTail: null, $$childHead: null, $$prevSibling: Scope, $$nextSibling: Scope…}
...
output: "3"
...

I know there is another question asking for pretty much the same but the OP is using an isolate scope with @ for an attribute whereas I'm using = which won't work with observe as much as I know.

And then there is something else I'm a little bit confused about. Why is that even possible, isn't a console.log() a "snapshot" of whats given as a parameter? So how is it possible that I see a property in line 1 and in line 2 it's undefined?

Was it helpful?

Solution

It's a general issue in JavaScript. I found this answer very helpful.

When you run console.log(this), you output the object itself and the console links references (pointers if you like) to the inner variables.

Same is valid for $scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top