变量在范围内未定义,但实际上已定义

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

我真是一头雾水,不知道这是怎么回事!

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

结果,

如图所示,botid 存在于 scope 中,但是当我尝试通过 [=11] 获取它时=] 它表明它不是 defined!

很可能,scope.botid 在打印时未定义,而是在 console.log 语句之后定义的。

当你在对象上使用console.log时,它显示了对象在JS执行结束时的状态。

不要只在 console.log 语句中使用范围,请尝试以下操作:

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

在范围变量上放置一个 $watch。控制将在监视处理函数中进行两次。你会看到发生了什么。 另外,您的 HTML 标记是什么,可能是您将其绑定到未定义。

由于 运行 控制器和 link 函数的顺序,您需要使用 $timeout 以允许变量加载到作用域中。这是我解决它的方法:

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