如何使用 AngularJS 访问浏览器控制台中的 $scope 变量?

如何使用 AngularJS 访问浏览器控制台中的 $scope 变量?

问题描述:

我想在 Chrome 的 JavaScript 控制台中访问我的 $scope 变量.我该怎么做?

I would like to access my $scope variable in Chrome's JavaScript console. How do I do that?

我在控制台中既看不到 $scope 也看不到我的模块名称 myapp 作为变量.

I can neither see $scope nor the name of my module myapp in the console as variables.

在开发者工具的 HTML 面板中选择一个元素并在控制台中输入:

Pick an element in the HTML panel of the developer tools and type this in the console:

angular.element($0).scope()

WebKit 和 Firefox 中,$0 是对在元素选项卡中选择 DOM 节点,因此通过这样做,您可以在控制台中打印出所选 DOM 节点范围.

In WebKit and Firefox, $0 is a reference to the selected DOM node in the elements tab, so by doing this you get the selected DOM node scope printed out in the console.

您还可以按元素 ID 定位范围,如下所示:

You can also target the scope by element ID, like so:

angular.element(document.getElementById('yourElementId')).scope()

插件/扩展

您可能想查看一些非常有用的 Chrome 扩展程序:

There are some very useful Chrome extensions that you might want to check out:

  • Batarang. This has been around for a while.

ng-inspector.这是最新的,顾名思义,它允许您检查应用程序的范围.

ng-inspector. This is the newest one, and as the name suggests, it allows you to inspect your application's scopes.

玩 jsFiddle

使用 jsfiddle 时,您可以通过在 URL 末尾添加 /showshow 模式打开 fiddle.像这样运行时,您可以访问 angular 全局.你可以在这里试试:

When working with jsfiddle you can open the fiddle in show mode by adding /show at the end of the URL. When running like this you have access to the angular global. You can try it here:

http://jsfiddle.net/jaimem/Yatbt/show

jQuery Lite

如果你在 AngularJS 之前加载 jQuery,angular.element 可以传递一个 jQuery 选择器.所以你可以用

If you load jQuery before AngularJS, angular.element can be passed a jQuery selector. So you could inspect the scope of a controller with

angular.element('[ng-controller=ctrl]').scope()

一个按钮

 angular.element('button:eq(1)').scope()

...等等.

您实际上可能想使用全局函数来简化操作:

You might actually want to use a global function to make it easier:

window.SC = function(selector){
    return angular.element(selector).scope();
};

现在你可以这样做了

SC('button:eq(10)')
SC('button:eq(10)').row   // -> value of scope.row

在这里查看:http://jsfiddle.net/jaimem/DvRaR/1/show/