Debug AngularJS applications through terminals
When we build AngularJS applications, it is always difficult to access the hidden data and services in applications through the JavaScript console of browsers such as Chrome, Firefox, and IE. The following are some simple tips to help us view or control the running Angular application through the Javascript console, so that the application can be easily tested and modified, even real-time modifications to our Angular application:
1: Access Scope
Access any scope or even isolated scope on the page through a simple JS program !) :
- > angular.element(targetNode).scope()
- -> ChildScope {$id: "005", this: ChildScope, $$listeners: Object, $$listenerCount: Object, $parent: Scope…}
For the isolation scope:
- > angular.element(targetNode).isolateScope()
- -> Scope {$id: "009", $$childTail: ChildScope, $$childHead: ChildScope, $$prevSibling: ChildScope, $$nextSibling: Scope…}
Here, 'targetnode' is used as an HTML node reference. You can easily create a 'targetnode' using 'document. querySelector'
2: view the scope tree
Sometimes, we need to view the scope level on the page to effectively debug our application. AngularJS Batarang is an extension of the Chrome browser we need. It can display the current scope level and has other very useful features.
3: capture any service
No matter where the ngApp is defined, we can use the injector function to capture references to any service. If the angular bootstrap method is used, we can manually capture $ rootElement ):
- > angular.element('html').injector().get('MyService')
- -> Object {undo: function, redo: function, _pushAction: function, newDocument: function, init: function…}
Then we can call the service, just as we can inject the service.
4: Access Controller instructions
Some commands define a controller with some additional features, usually shared. To access a controller instance with a given command from the console, you only need to use the controller () method:
- > angular.element('my-pages').controller()
- -> Constructor {}
The last approach is more advanced and not commonly used.
5: Chrome console features
The Chrome console has a bunch of good shortcuts to debug browser applications. This is the best practice for Angular development:
-
$0-$4: Access the 5 most recently selected DOM elements in the View window. It is very convenient to select the capture range.
-
$ (Selector) and $ (selector): A quick alternative to querySelector () and querySelectorAll.
Thanks @ zgohr for providing this method!
Conclusion
With a few simple tips, we can access the data in any scope on the page, view the scope hierarchy, inject services and control commands.
So next time, if you want to adjust it a little, check your work, or control AngularJS using the console, I hope you can remember these commands, and I think they are very practical!
Debugging AngularJS Apps from the Console
By http://www.oschina.net/translate/angularjs-console