[转]调试AngularJS应用

原文链接:Debugging AngularJS Apps from the Console

  当我们开发AngularJS应用的时候,我们想在Chrome/FF/IE控制台调试隐藏在应用中的数据和服务的很困难的,下面是一些小技巧,可以来检测和监控正在运行的应用程序,这使我们开发、调试、修改angular应用变的较为容易。

1.Access Scopes
我们可以访问任何作用域(甚至一个独立作用域),在页面使用单行JS即可实现:

1 > angular.element(targetNode).scope()
2 -> ChildScope {$id: "005", this: ChildScope, $$listeners: Object, $$listenerCount: Object, $parent: Scope…}

或者一个隔离的作用域:

1 > angular.element(targetNode).isolateScope()
2 -> Scope {$id: "009", $$childTail: ChildScope, $$childHead: ChildScope, $$prevSibling: ChildScope, $$nextSibling: Scope…}

其中targetNode是节点Dom对象,可以使用document.getElementById(),document.querySelector()等来获取。如果你不知道querySelector方法如何使用及兼容性问题,请戳这里

2.Inspect the Scope Tree
可以使用Chrome的AngularJS BataRang插件。
angular-batarang

3.Grab any Services
可以通过注入服务的ngApp,或者.ng-scope类名来调用:

1 > angular.element(document.querySelector('html')).injector().get('MyService')
2 -> Object {undo: function, redo: function, _pushAction: function, newDocument: function, init: function…}
3 // Or slightly more generic
4 > angular.element(document.querySelector('.ng-scope')).injector().get('MyService')

这是我们就可以调用服务的方法了,就想我们注入了服务,我们可以调用服务的方法一样。

4.Access controller for directive
Some directives define a controller with certain additional (often shared) functionality. To access the instance of a controller for a given directive from the console, just use the controller() function:
在我们定义的时候,会把一些公共的功能放到控制器中,为了访问控制器的实例,我们只要使用controller()方法就可以:

1 > angular.element('my-pages').controller()
2 -> Constructor {}

5.Chrome Console Features
Chrome我们提供一些好的快捷方式,在控制台中debug 我们的浏览器应用,在AngularJS开发中,下面有些最好的方式:
a)$0 – $4: Access the last 5 DOM elements selected in the inspector window. This is convenient for grabbing scopes for selected elements: angular.element($0).scope()

b)$(selector) and $$(selector): A quick replacement for querySelector() and querySelectorAll, respectively.

原文地址:https://www.cnblogs.com/dajianshi/p/4500025.html