KodeBLOG

Kode Blog - Inspiring And Empowering Developers.

Home About Us Courses Categories Blog Contact Us

AngularJS Debug

Introduction

Figuring out what went wrong in a simple application is very straight forward. But when you develop large applications on AngularJS and you do not get the expected results, it is trick to figure out what went wrong. Most web browsers won’t alert you when an error occurs. This tutorial shows you some of the tools that will make it easy for you to debug your applications.

Topics to be covered

We will cover the following topics in this tutorial

  • Common errors
  • AngularJS Debug tutorial project
  • Firefox firebug
  • Google chrome Developer Tools
  • ng-inspector for AngularJS
  • Google chrome AngularJS Batarang extension
  • What is the best debugging tool?

Common errors

AngularJS is a JavaScript framework and you will be writing pure JavaScript code from time to time. This means some of the errors that you will be encountering will not be unique to AngularJS but JavaScript in general. The following list shows some of the issues that you will need to pay attention to when writing JavaScript. It’s not an exhaustive list because this tutorial is more specific to AngularJS.

  1. Case sensitivity – variable names, methods etc. are all sensitive. $Scope is not the same as $scope. Paying attention to the casing of the variables, properties and methods will save you a lot of debugging time
  2. Syntax errors – most IDEs will usually close the quotation marks for you when working with strings. If the IDE closes the quotation for you and then you add an extra one then that will cause a problem for you. Do you have opening and closing braces/parenthesis etc.?
  3. Accidentally using an assignment operator for comparison – this is one of the trick ones to figure out especially if you are tired. You won’t get any error messages and the desired results.

AngularJS Debug tutorial project

Let’s create a simple project that will load JSON data and display scope variable data from controllers. I am assuming you have a working web server and that is where you will create the project.

Application Directories and Files

Our simple application will have the following directories and files

Application structure

  1. Create a directory angularjs-debug in your web root
  2. Create a directory app inside angularjs-debug directory
  3. Create a directory controllers inside app directory
  4. Create a directory js inside angularjs-debug directory

index.html

Create an index.html file in your root directory and add the following code

<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<title>AngularJS  Tutorial Series</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div  ng-controller="HelloController">Hi {{name}}, welcome to AngularJS Tutorial Series</div>

<div ng-controller="AboutController">Brought to you by {{name}}.</div>

        <h2>Load me some JSON data : )</h2>
        <table ng-controller="HelloController">
          <tr>
            <th>Name</th>
            <th>City</th>
            <th>Country</th>
          </tr>
          <tr ng-repeat="country in countries">
            <td>{{country.Name}}</td>
            <td>{{country.City}}</td>
            <td>{{country.Country}}</td>
          </tr>
        </table>
<!-- Angular JS Scripts -->
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>

<!-- AngularJS Application Specific Scripts -->
<script src="app/app.js"></script>
<script src="app/controllers/homeController.js"></script>
<script src="app/controllers/aboutController.js"></script>
</body>
</html>

Create a new file countries.json and add the following data

{
"records": [
  {
    "Name" : "Alfreds Futterkiste",
    "City" : "Berlin",
    "Country" : "Germany"
  },
  {
    "Name" : "Centro comercial Moctezuma",
    "City" : "México D.F.",
    "Country" : "Mexico"
  },
  {
    "Name" : "Ernst Handel",
    "City" : "Graz",
    "Country" : "Austria"
  },
  {
    "Name" : "FISSA Fabrica Inter. Salchichas S.A.",
    "City" : "Madrid",
    "Country" : "Spain"
  },
  {
    "Name" : "Island Trading",
    "City" : "Cowes",
    "Country" : "UK"
  }
]
}

app.js

Create a new file app.js in app directory and add the following code

var MyApp = angular.module("MyApp", []);

homeController.js

Create a new file homeController.js in /app/controllers/homeController.js

Add the following code

MyApp.controller('HelloController', hello);

function hello($scope){
    $scope.name = "Rodrick";

    $http.get('countries.json').success(function(data) {
          $scope.countries = data.records;
    });
}

aboutController.js

Create a new file aboutController.js in /app/controllers/aboutController.js

Add the following code

MyApp.controller('AboutController', about);

function about($scope)
{
    $scope.name = "Kode Blog Tutorials";
}

js directory

Download and save angular.min.js and angular-route.min.js in /js directory If you are new to AngularJS and the above code doesn’t make sense then I recommend you read the tutorial AngularJS Hello World. The tutorial explains what the above code does.

Firefox firebug ##

Application structure

Most browsers handle errors silently and still return the results to the user. It’s difficult to tell if any error has occurred or not.

Load the following URL into your browser to view the application. Note the URL should point to the web directory that you created.

http://localhost/angular-tuts/angularjs-debug/

You will get the following results

Application structure

HERE

  • Hi {{name}}, is the variable name that should have been replaced with the variable value.
  • Brought to you by {{name}} is the variable name that should have been replaced with the variable value.

Firebug is a Firefox web browser add-on that detects errors and displays them in the console when they occur.

Firebox can be used to debug JavaScript code in generally and not specifically for AngularJS. You can download Firebug from Getfirebug. You can read more about Firebug from the official website.

Once you have successfully installed Firebug, you will see the firebug icon on the toolbar. Click on it to activate it.

Reload the following URL in your browser

http://localhost/angular-tuts/angularjs-debug/

You will get an error notification on the firebug icon as shown in the image below

Application structure

HERE,

  1. Error notification – this notifies you of the number of errors that have occurred.
  2. The console at the bottom of the browser provides detailed information about the error ReferenceError: $http is not defined. This is because we are trying to use the Angular service $http which we did not pass as a parameter to the function hello
  3. hello is the name of the function where the error occurred.
  4. homeController.js (line 6) gives us the name of the file where the error occurred and the line number.
  5. If you click on the scripts tab, you will be able to see the code that caused the error.
  6. Shows the file name that has been loaded in the scripts tab.

As you can see from the above image, Firebug is pure awesomeness in the world of debugging : )

The above error can be fixed by passing $http service as a parameter to the function hello as shown below.

function hello($scope,$http){
    $scope.name = "Rodrick";

    $http.get('countries.json').success(function(data) {
          $scope.countries = data.records;
    });
}

Firebug allows allow you to set break points in your code. Execution is halted when the breakpoint is reached and you can examine what the code id doing and what data it has when it breaks.

Google chrome Developer Tools

Google chrome web browser has built-in developer tools that can be used to debug JavaScript code too among other things. If you included the $http service in hello function then remove it so that we can use Google chrome developer tools to catch the error.

Load the following URL

http://localhost/angular-tuts/angularjs-debug/

The program will not display the variable values nor the table.

Press F12 on the keyboard to display the developer tools

You will get the following

Application structure

HERE,

  1. Sources tab – click on the sources tab to view the above information
  2. Error notification – 1 error has occurred
  3. The console shows detailed information about the error. ReferenceError: $http is not defined. It also shows the file name where the error occurred and line number 6.
  4. This section allows you to view public directories and files on the server.

ng-inspector for AngularJS

Firebug and Google chrome developer are great for catching errors. ng-inspector can be used to view data returned by the application. ng-inspector works in Google chrome, Firefox and safari. You can download it from the official website ng-inspector.org

After successfully installing ng-inspector for AngularJS, you will get the AngularJS logo in your web browser toolbar as shown in the image below

Application structure

Fix the above error by updating the function hello as follows

function hello($scope,$http){
    $scope.name = "Rodrick";

    $http.get('countries.json').success(function(data) {
          $scope.countries = data.records;
    });
}

For this example, I will be using Firefox but you can use your favourite browser that is supported.

Load the following URL

http://localhost/angular-tuts/angularjs-debug/

You will get the following results

Click on the icon for ng-inspector

You will get the following results

Application structure

ng-inspector will display a panel in the browser

HERE,

  1. Shows the module name of the current active AngularJS application
  2. Hovering over HelloController highlights the HTML section on the page that is being manipulated by HelloController
  3. Dynamically generated content from HelloController

If you click on an element from the ng-inspector panel, it will be printed in the console window

Application structure

Google chrome AngularJS Batarang extension

AngularJS Batarang extension is developer by the Google team behind AngularJS framework, It is a tool for debugging and profiling AngularJS application. You can download it from the Chrome web store. This extension only works in Google chrome.

AngularJS Batarang extension is added to the developer tools

Load the following URL in Google chrome

http://localhost/angular-tuts/angularjs-debug/

Press F12 on the keyboard to display developer tools

Application structure

Click on AngularJS tab

You will get various sub tabs i.e. Models, Performance, Dependencies, Options and Help.

Click on Enable check button

Models

This tab allows you to view the scopes and model data.

Application structure

Performance

Shows information about the application’s performance. It shows you how long it takes for each data element to load.

Application structure

Dependencies

Displays a graph for the application dependencies

Options

Allows you to display application boundaries, data bindings and scopes

Application structure

What is the best debugging tool?

The answer to the above questions is none. It depends on what you want to accomplish and what web browser you prefer working with. Other tools such as Firebug and Google chrome developer tools are good at catching bugs. ng-inspector and Batarang I usually use them to inspecting values and profiling applications for performance.

Summary

AngularJS debugging is made easy and beautiful when you work with tools such as the ones above. The tool that you choose depends on what you want to accomplish.

What’s next?

The next tutorial will teach you how to work with modules in AngularJS.

If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.

Each week, a new AngularJS tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.

Tutorial History

Tutorial version 1: Date Published 2015-09-28