为什么我有一个未定义的作用域?angularjs

Why do I have a not defined scope ? angularjs

本文关键字:作用域 angularjs 未定义 有一个 为什么      更新时间:2023-09-26

我试图从范围中"提取"一个值。然而,我得到一个错误,没有定义,通过我不明白为什么。这是来自Chrome dev

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

第一个打印"undefined",第二个打印如下。我期望$scope。命令输出对象

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

这有什么原因吗?

$$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

您没有显示完整的代码,但它可能发生,因为当您运行console.log时auth对象不存在(您可能从异步服务调用等中获取它)。它仍然会出现在console.log($scope)调用中,因为控制台在展开变量时显示变量的当前状态。因此,当您在控制台中展开$scope变量时,它的auth对象已经定义并设置好了。

下面是一个超时的例子(模拟任何异步事件):

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

在这里查看完整的示例(检查控制台):http://plnkr.co/edit/uqJVzfYNoJ0KCRGZawdW?p=preview

此外,您将在这里找到一些与此相关的很好的解释:我如何更改console.log的默认行为?(* safari中的错误控制台,没有附加组件*)


因此,底线是:您将无法"提取"该作用域值,仅仅因为它在那时不可用。展示更多的代码,我们将帮助您确定何时可用。