【问题标题】:What would prevent access to AngularJS $scope from browser console?什么会阻止从浏览器控制台访问 AngularJS $scope?
【发布时间】:2015-11-17 02:16:29
【问题描述】:

我过去做过几个使用 AngularJS 的项目。在开发过程中,我总是能够在浏览器控制台中调用 $scope,从而调用它的所有变量。例如,$scope.myArray 将返回类似 [][object1, object2] 的内容。

但是,现在当我输入 $scope 时,我得到:

Uncaught ReferenceError: $scope is not defined

我也看过How to access the $scope variable in browser's console using AngularJS?之类的其他帖子,建议使用angular.element($0).scope(),但是当我在控制台中输入时,我得到:

未定义

我无法访问像myArray 这样的对象,即使我知道它正在被创建。有谁知道发生了什么变化?

编辑:当我尝试以前可以访问 $scope 的项目中的代码时,我也遇到了这个问题,所以这让我认为这不是一个简单的实现错误。

【问题讨论】:

  • 它仍然适用于依赖注入,任何地方都在玩
  • $0 可能没有引用正确的元素。为您的元素找到一个选择器(例如,通过检查元素,在“元素”面板中右键单击它,然后单击“获取 CSS 路径”),然后执行 angular.element(theCssPath).scope()
  • 我在 chrome 中使用 AngularJS Batarang,这使我可以在控制台中输入 $scope。你是不是也用过这个扩展,卸载后不小心忘记了?
  • @TjaartvanderWalt 感谢您推荐 Batarang。这将有助于我进行调试,即使我仍然希望拥有从控制台中调用 $scope 的旧能力。

标签: javascript angularjs console angularjs-scope


【解决方案1】:

$0 是对元素选项卡中选定 DOM 节点的引用,因此通过这样做,您可以在控制台中打印出选定的 DOM 节点范围。

您必须先获取元素。 或者你可以只获得指定的范围。 例如:

angular.element('‪#‎element‬').scope();

angular.element(document.getElementsByTagName("button")[0]).scope()

https://jsfiddle.net/fatb8g3z/

【讨论】:

  • 我仍然无法让它工作。我输入了angular.element("button").scope();,得到了这个:Uncaught Error: [jqLite:nosel] http://errors.angularjs.org/1.3.14/jqLite/nosel
  • 这是 jqLit​​e 的问题。试试这个。 angular.element(document.getElementsByTagName("button")[0]).scope()
【解决方案2】:

在控制器的定义中放入window.myScope = $scope。然后在控制台中,您可以调用myScope.myArray 将内容返回给您。

例如:

var app = angular.module('myApp', [])

app.controller('myCtrl', function($scope) {
window.myScope = $scope; //this allows console access

$scope.myArray = [];
//more code here
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2011-05-20
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多