Debugging AngularJS applications with Chrome DevTools

Loading

Debugging is crucial for developing AngularJS applications. Chrome DevTools provides powerful features for debugging, inspecting, and optimizing AngularJS applications.

In this guide, we will cover:

  1. Enabling and Opening Chrome DevTools
  2. Inspecting the AngularJS Scope
  3. Debugging AngularJS Controllers and Services
  4. Monitoring HTTP Requests
  5. Using Breakpoints for Debugging
  6. Profiling Performance
  7. Debugging with AngularJS-Specific Extensions
  8. Best Practices for Effective Debugging

1. Enabling and Opening Chrome DevTools

Opening DevTools

You can open Chrome DevTools in multiple ways:

  • Right-click on an element → Click Inspect.
  • Press F12 or Ctrl + Shift + I (Windows/Linux).
  • Press Cmd + Option + I (Mac).

2. Inspecting the AngularJS Scope

Using $scope in the Console

AngularJS applications use the $scope object to bind data between the view and the controller. You can inspect the scope of an element in Chrome DevTools:

  1. Open DevTools and go to the Elements tab.
  2. Select an AngularJS-bound element.
  3. In the Console, run: jsCopyEditangular.element($0).scope()
    • $0 refers to the currently selected element.
    • This command prints the scope object in the console.

Checking $scope Variables

To check specific variables inside the scope:

angular.element($0).scope().myVariable

You can also modify the scope value dynamically:

angular.element($0).scope().myVariable = 'New Value';
angular.element($0).scope().$apply(); // To reflect changes in UI

3. Debugging AngularJS Controllers and Services

Logging from Controllers

To check if a controller is working correctly, add:

console.log('Controller Loaded');

or

console.log($scope.myVariable);

Debugging Services

If you suspect an issue with a service, inject it into the console:

angular.element(document.body).injector().get('myService')

This will retrieve the service instance, allowing you to inspect its methods and properties.


4. Monitoring HTTP Requests

AngularJS applications often interact with REST APIs using $http or $resource. Chrome DevTools provides tools to inspect these network requests.

Using the Network Tab

  1. Open DevTools → Go to the Network tab.
  2. Filter requests using “XHR” (for AJAX calls).
  3. Click on a request to inspect:
    • Headers: See request/response headers.
    • Response: Check the API response.
    • Timing: Analyze request duration.

Intercepting $http Calls

To debug HTTP requests from AngularJS, use:

angular.element(document.body).injector().get('$http')

This retrieves the $http service instance.


5. Using Breakpoints for Debugging

Breakpoints allow you to pause execution and inspect the code.

Setting Breakpoints in DevTools

  1. Open DevTools → Go to the Sources tab.
  2. Open the relevant JavaScript file.
  3. Click on the line number to set a breakpoint.

Conditional Breakpoints

Right-click a breakpoint → Choose Edit breakpoint, then enter:

$scope.myVariable === 'error'

This pauses execution only when a condition is met.

Using debugger; Statement

Manually pause execution by inserting:

debugger;

into your AngularJS code. Execution will stop when Chrome DevTools is open.


6. Profiling Performance

AngularJS can sometimes suffer from performance bottlenecks due to frequent digest cycles. Chrome DevTools provides profiling tools to analyze performance.

Using Timeline for Performance Analysis

  1. Open DevTools → Go to the Performance tab.
  2. Click Record and interact with your application.
  3. Stop the recording to analyze:
    • Long-running JavaScript functions.
    • Repaints and reflows.
    • Slow event handlers.

7. Debugging with AngularJS-Specific Extensions

Using AngularJS Batarang

AngularJS Batarang is a Chrome extension designed for debugging AngularJS apps.

Features of Batarang

  • Displays scope hierarchy.
  • Highlights dirty $digest cycles.
  • Inspects dependencies and bindings.

How to Use Batarang

  1. Install Batarang from the Chrome Web Store.
  2. Open DevTools → Click the AngularJS tab.
  3. Select an AngularJS app from the list.
  4. Explore scopes, bindings, and performance metrics.

8. Best Practices for Effective Debugging

Use $scope.$watch for Tracking Variable Changes

$scope.$watch('myVariable', function(newValue, oldValue) {
console.log('Value changed from', oldValue, 'to', newValue);
});

Use $log Instead of console.log AngularJS provides the $log service, which can be toggled off in production:

app.controller('MyController', function($scope, $log) {
$log.debug('This is a debug message');
});

Use $exceptionHandler to Catch Errors

app.factory('$exceptionHandler', function() {
return function(exception, cause) {
console.error('AngularJS Error:', exception, 'Cause:', cause);
};
});

Optimize the Digest Cycle Use track by in ng-repeat to prevent excessive digest cycles:

<li ng-repeat="item in items track by item.id">{{ item.name }}</li>

Avoid Memory Leaks Destroy watchers and listeners when not needed:

$scope.$on('$destroy', function() {
myListener();
});

Leave a Reply

Your email address will not be published. Required fields are marked *