OdeToCode IC Logo

Debugging AngularJS In The Console

Tuesday, July 29, 2014

Although Batarang gets a lot of attention, there may come a time when you need to dig a bit deeper into an Angular application, particularly if you are debugging or spelunking someone else’s application and you aren’t familiar with the entire code base.

Here are some tricks I’ve learned.   

Find The Scope For An Element

Update: note  David Boike's comment- "When you have Batarang installed in Chrome, no need to type out angular.element($0).scope() - Batarang makes the scope of the last clicked element available in the console as '$scope'"

A non-trivial page built with Angular will have dozens of scopes containing model information for controllers, directives, transclusions, and repeaters. Although Batarang provides a clickable hierarchy of scopes on the Models tab, it’s sometimes difficult to find the exact scope you need.

Batarang showing all the models

In these scenarios I’ve found it faster to use Chrome’s $0 symbol in the developer tools console window.

You’ve never used $0? Here is an excerpt from the Chrome console documentation:

Often when testing you'll select DOM elements—either directly in the Elements panel or using the Selection tool (magnifying glass)—so that you can further inspect the element.

The Console remembers the last five elements (or heap objects) you've selected and makes them available as properties named $0, $1, $2, $3 and $4. The most recently selected element or object is available as $0, the second most as $1, and so forth.

 

Once you have an element reference, you can wrap the element with angular.element and use the scope method to retrieve the associated scope.

Using $0 to find a scope

Once you have the scope, you can drill in to see details, or take the $id property to find the scope in Batarang’s display.

Evaluate Binding Expressions

If an element has an ng-binding attribute present, you’ll find the function used to execute the binding in the data property of the element. Combine the function with a scope object or a custom object (if you want to tinker with the binding), to see what the binding function produces.

angular binding The data of an element can also hold other interesting pieces of information, like a reference to a controller.

Interact With Services

The injector method gives you access to the single injector for an application, and the injector can give you access to any service from the application. Using a service interactively allows you to play with the service, debug it, pass it strange parameters, and watch to see how it behaves.

ng services in the console

One last tip: you can always check the version of Angular a page is using by typing angular.version in the console.