javascript
[转]调试AngularJS应用
原文鏈接:Debugging AngularJS Apps from the Console
當(dāng)我們開發(fā)AngularJS應(yīng)用的時候,我們想在Chrome/FF/IE控制臺調(diào)試隱藏在應(yīng)用中的數(shù)據(jù)和服務(wù)的很困難的,下面是一些小技巧,可以來檢測和監(jiān)控正在運行的應(yīng)用程序,這使我們開發(fā)、調(diào)試、修改angular應(yīng)用變的較為容易。
1.Access Scopes
我們可以訪問任何作用域(甚至一個獨立作用域),在頁面使用單行JS即可實現(xiàn):
| 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是節(jié)點Dom對象,可以使用document.getElementById(),document.querySelector()等來獲取。如果你不知道querySelector方法如何使用及兼容性問題,請戳這里。
2.Inspect the Scope Tree
可以使用Chrome的AngularJS BataRang插件。
3.Grab any Services
可以通過注入服務(wù)的ngApp,或者.ng-scope類名來調(diào)用:
| 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') |
這是我們就可以調(diào)用服務(wù)的方法了,就想我們注入了服務(wù),我們可以調(diào)用服務(wù)的方法一樣。
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 我們的瀏覽器應(yīng)用,在AngularJS開發(fā)中,下面有些最好的方式:
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.
?
總結(jié)
以上是生活随笔為你收集整理的[转]调试AngularJS应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#学习笔记-stream,win8.1
- 下一篇: 【转载】linux 下 cpu使用情况分