Home > Article > Web Front-end > How to debug AngularJS applications using Chrome browser_AngularJS
When we build AngularJS applications, it is always a bit difficult to access hidden data and services in the application through the JavaScript console of browsers such as Chrome, Firefox and IE. Here are some simple techniques that can help us view or control running Angular applications through the Javascript console, making it easier to test, modify, and even modify our Angular applications in real time:
1: Access scope
Access any scope in the page (even isolated scopes!) with a simple line of JS:
> angular.element(targetNode).scope() -> ChildScope {$id: "005", this: ChildScope, $$listeners: Object, $$listenerCount: Object, $parent: Scope…}
For isolation scope:
> angular.element(targetNode).isolateScope() -> Scope {$id: "009", $$childTail: ChildScope, $$childHead: ChildScope, $$prevSibling: ChildScope, $$nextSibling: Scope…}
Use `targetNode` here as a reference to the HTML node. You can easily create a `targetNode` through `document.querySelector()`
2: View scope tree
Sometimes, we need to view the scope hierarchy in the page to effectively debug our application. AngularJS Batarang is exactly what we need, a Chrome browser extension that can display the current scope hierarchy and has other very useful features.
3: Grab any service
No matter where ngApp is defined, we can use the injector function to grab a reference to any service (if you use angular’s bootstrap method, you can manually grab $rootElement):
> angular.element('html').injector().get('MyService') -> Object {undo: function, redo: function, _pushAction: function, newDocument: function, init: function…}
We can then make calls to the service, just like we can inject the service.
4: Access controller usage instructions
Some directives define a controller with some additional (usually sharing) functionality. To access a controller instance for a given directive from the console, simply use the controller() method:
> angular.element('my-pages').controller() -> Constructor {}
The last approach is more advanced and less commonly used.
5: Chrome console features
Chrome’s console has a bunch of great shortcuts for debugging browser apps. Here are some of the best practices in Angular development:
Thanks @zgohr for providing this method!
Conclusion
With a few simple tricks, we can access data in any scope of the page, view the scope hierarchy, inject services and control instructions.
So next time, if you want to tweak a little, check your own work or control an AngularJS application through the console, I hope you can remember these commands and find them as useful as I did!