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:
- Enabling and Opening Chrome DevTools
- Inspecting the AngularJS Scope
- Debugging AngularJS Controllers and Services
- Monitoring HTTP Requests
- Using Breakpoints for Debugging
- Profiling Performance
- Debugging with AngularJS-Specific Extensions
- 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:
- Open DevTools and go to the Elements tab.
- Select an AngularJS-bound element.
- In the Console, run: jsCopyEdit
angular.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
- Open DevTools → Go to the Network tab.
- Filter requests using “XHR” (for AJAX calls).
- 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
- Open DevTools → Go to the Sources tab.
- Open the relevant JavaScript file.
- 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
- Open DevTools → Go to the Performance tab.
- Click Record and interact with your application.
- 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
- Install Batarang from the Chrome Web Store.
- Open DevTools → Click the AngularJS tab.
- Select an AngularJS app from the list.
- 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();
});