Emad Ghasemi
Emad Ghasemi

Reputation: 396

Variable is undefined in the scope, but it's actually defined

I'm really confused, I don't know what heck is going on!

.directive("blGraph", ['$http', function($http) {
  return {
    restrict: 'EA',
    scope: {
      botid: "=blGraph"
    },
    link: function(scope, element, attr) {
      console.log(scope, scope.botid);
    }
  };
}]);

Result,

enter image description here

as you see in the picture, the botid exist in the scope, but when i try to get it by scope.botid it tell that it is not defined!

Upvotes: 0

Views: 888

Answers (3)

Michael Blasius
Michael Blasius

Reputation: 21

Due to the sequence of running the controller and link functions, you need to use a $timeout in order to allow the variables to load onto the scope. Here's how I solved it:

  controller: function($scope, $timeout) {
     $timeout(function(){
        console.log($scope.myVariable)
     },0);
  }

Upvotes: 1

srjt
srjt

Reputation: 316

put a $watch on the scope variable. Control will go twice in the watch handler function. You will see what is happening. Also what is your HTML markup, may be you are binding it to undefined.

Upvotes: 1

jperezov
jperezov

Reputation: 3181

Most likely, scope.botid is not defined when you are printing it, and is defined after the console.log statement.

When you use console.log on an object, it shows the state of the object at the end of the JS execution.

Instead of just using scope in the console.log statement, try the following:

console.log(JSON.stringify(scope), scope.botid);

Upvotes: 0

Related Questions