hey
hey

Reputation: 7859

Why do I have a not defined scope ? angularjs

I'm trying to 'extract' a value from scope. However I get an error that is not defined, through I don't understand why. This is from Chrome dev

  console.log($scope.auth)
  console.log($scope)

The first one prints "undefined" and the second one prints as follows. I expected $scope.auth to print the object

auth: Object
Owner: "agent2"
Role: "coldCalling"

Is there any reason for this ?

$$childScopeClass {$$childTail: null, $$childHead: null, $$nextSibling: null, $$watchers: null, $$listeners: Object…}
$$childHead: null
$$childScopeClass: null
$$childTail: null
$$listenerCount: Object
$$listeners: Object
$$nextSibling: null
$$prevSibling: null
$$watchers: null
$id: "002"
$parent: Scope
auth: Object
   Owner: "agent2"
   Role: "coldCalling"
__proto__: Object
this: $$childScopeClass
__proto__: Scope

Upvotes: 1

Views: 542

Answers (1)

Shomz
Shomz

Reputation: 37711

You didn't show the full code, but it's probably happening because the auth object did not exist when you ran console.log (you're probably fetching it from an async service call, etc.). It would still appear in the console.log($scope) call because console shows the current state of a variable when you expand it. So by the time you expand the $scope variable in the console, its auth object is defined and set.

Here's an example with a timeout (to simulate any async event):

setTimeout(function(){
  $scope.auth = {'Owner': 'Test', 'Role': 'Role'};
}, 1000);
console.log($scope.auth);   // undefined
console.log($scope);        // auth object exists when you expand it in the console

See the full example here (check the console): http://plnkr.co/edit/uqJVzfYNoJ0KCRGZawdW?p=preview

Also, you'll find some nice explanations related to that here: How can I change the default behavior of console.log? (*Error console in safari, no add-on*)


So, the bottom line: you won't be able to "extract" that scope value simply because it's unavailable at that point. Show some more code and we'll help you figure out when it becomes available.

Upvotes: 2

Related Questions