Creating a Visualization App Using the Google Charts API and AngularJS

Share this article

Nowadays, JavaScript is everywhere. A number of useful JavaScript frameworks like Ember.js, Backbone.js, etc. are changing the face of the Web. Among the most popular frameworks is AngularJS, developed by Google. This article, the first of three, will teach you how to build a visualization app using AngularJS. The example app will visualize data using the Google Charts API. We’ll be using one of the awesome two-way binding features of Angular to make our charts dynamically change as per change in data and user input. Before getting started, let’s first take a look at how to use the Google Charts API. For the purposes of this app, we’ll stick to some basic charts like line charts, pie charts, etc.

Google Charts

Straight from the Google Charts documentation, the following example gives a quick refresher on how to use the Google Charts API. The first script loads the AJAX API. Inside the second script, the first line loads the Visualization API and the linechart package. The second line sets a callback to run when the Google Visualization API is loaded. The callback function creates a data table, sets a few chart options, instantiates our chart, and creates the chart.
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1', {packages:['corechart']});
      google.setOnLoadCallback(drawChart);

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);
        var options = {
          title: 'Company Performance'
        };
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>
If you are new to this API, or need a refresher, I would recommend reading the Google Charts documentation.

AngularJS

Before getting started with Angular, you should: From the terminal, navigate to the seed project and then, enter the following commands: cd angular-seed node scripts/web-server.js You should see the following message output to the console: HTTP Server running at http://localhost:8000/ At this point, you can view the demo page by navigating to http://localhost:8000/app/index.html. Angular uses the MVC (Model-View-Controller) design pattern. In this tutorial, we’ll be focusing on the Controllers. For the time being, consider a Controller to be logic which handles a particular portion of a page and renders the data using a View. We’ll get a better picture of what Controllers are once we get started with writing the app. Now, let’s have a look at the angular seed project. It is an Angular app template that we’ll be building our app on top of. Inside the angular seed project navigate to app/js. There, we can see controllers, directives, app, filters, and services. These are the things we’ll be playing around with while creating our app.

Building the App

Replace the code inside index.html with the following code:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>My AngularJS App</title>
</head>
<body>
  <div ng-controller="MyCtrl1">{{name}}</div>
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-route.js"></script>
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>
</body>
</html>

The Controller

As previously mentioned, a Controller contains logic which handles a particular portion of a page. In the previous code sample notice the following line:
<div ng-controller="MyCtrl1">{{name}}</div>
This div has a ng-controller attribute whose value is MyCtrl1. MyCtrl1 is the name of a controller function found in the file app/js/controllers.js
. The ng-controller attribute is referred to as a directive. Angular directives are used to enhance HTML, and the ng-controller directive is used to set the controller for a particular section of the page. {{name}} is the variable used to pass data from the controller to the view. Now, the question is, how do we access the variable name inside the MyCtrl1 controller. That’s where $scope comes into the picture. $scope is an object which act as a communication mechanism between a controller and a view. Examine the modified controllers.js code below:
'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
  controller('MyCtrl1', ['$scope',
    function($scope) {
      $scope.name = 'Jay';
    }
])
  .controller('MyCtrl2', [
    function() {

    }
]);
In the previous code, we are passing $scope as a parameter and setting the variable name. Now, simply restart the Node.js server using the following command. node scripts/web-server.js Now, pointing the browser URL to http://localhost:8000/app/index.html, should show you the name.

Creating Charts

Now, let’s draw some charts. First, include the Ajax API in index.html.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
Next, modify the div inside index.html
as shown below.
<div ng-controller="MyCtrl1" id="chartdiv"></div>
In controllers.js load the visualization API and the linechart package.
google.load('visualization', '1', {packages:['corechart']});
Once the package is loaded, we need to initialize our Angular app.
google.setOnLoadCallback(function() {
  angular.bootstrap(document.body, ['myApp']);
});
angular.bootstrap is a global API for manually starting an Angular app. Simply copy and paste the Google Chart creation code into the controller function and this is what we end up with:
'use strict';

/* Controllers */
google.load('visualization', '1', {
  packages: ['corechart']
});

google.setOnLoadCallback(function() {
  angular.bootstrap(document.body, ['myApp']);
});

angular.module('myApp.controllers', []).
  controller('MyCtrl1', ['$scope',
    function($scope) {
      var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2004', 1000, 400],
        ['2005', 1170, 460],
        ['2006', 660, 1120],
        ['2007', 1030, 540]
      ]);
      var options = {
        title: 'Company Performance'
      };
      var chart = new google.visualization.LineChart(document.getElementById('chartdiv'));

      chart.draw(data, options);
    }
  ])
    .controller('MyCtrl2', [
      function() {

      }
  ]);
Before running the code, edit index.html and remove ng-app="myApp" from the html tag. ng-app bootstraps the element with the app. However, since we’re already doing that in our controller code (with the following line of code), we can remove it from the HTML.
angular.bootstrap(document.body, ['myApp']);
Restart the Node server and visit http://localhost:8000/app/index.html. You should see a line chart based on our dummy data.

Conclusion

In this part of the tutorial we focused on Angular controllers. In the next article, we’ll be focusing on the use of directives and $scope. In the meantime, all of the code from this article is available on GitHub.

Frequently Asked Questions (FAQs) about Creating Visualization App using Google Charts API and AngularJS

How can I customize the appearance of my Google Charts?

Google Charts API provides a wide range of customization options that allow you to modify the appearance of your charts. You can change the colors, fonts, grid lines, and much more. To customize your chart, you need to modify the options object in your chart’s draw() method. For example, to change the title of your chart, you can use the following code:

var options = {
title: 'My Custom Title'
};

chart.draw(data, options);
Remember, the options object can contain many properties, allowing you to customize your chart extensively.

How can I add interactivity to my Google Charts?

Google Charts API provides several ways to add interactivity to your charts. One of the most common ways is to use the ‘select’ event, which is triggered when the user selects an item on the chart. You can add an event listener to your chart that listens for the ‘select’ event and performs an action when it is triggered. Here’s an example:

google.visualization.events.addListener(chart, 'select', function() {
var selectedItem = chart.getSelection()[0];
if (selectedItem) {
var value = data.getValue(selectedItem.row, selectedItem.column);
alert('You selected: ' + value);
}
});
In this example, when the user selects an item on the chart, an alert box will appear displaying the value of the selected item.

How can I use Google Charts with AngularJS?

To use Google Charts with AngularJS, you can use the angular-google-charts package. This package provides a set of AngularJS directives that make it easy to integrate Google Charts into your AngularJS application. To install the package, you can use the following command:

npm install angular-google-charts
Once the package is installed, you can use the directives provided by the package to create and customize your charts.

How can I join multiple DataTables in Google Charts?

Joining multiple DataTables in Google Charts can be achieved using the google.visualization.data.join() method. This method takes three DataTables as parameters: the first DataTable, the second DataTable, and a key column for each DataTable. The method returns a new DataTable that contains the rows from both DataTables where the key column values match. Here’s an example:

var joinedData = google.visualization.data.join(dataTable1, dataTable2, 'full', [[0, 0]], [1, 2], [1, 2]);
In this example, dataTable1 and dataTable2 are joined on the first column of each DataTable.

What types of charts can I create with Google Charts?

Google Charts API supports a wide variety of chart types, including line charts, bar charts, pie charts, scatter charts, area charts, and many more. Each chart type is represented by a specific class in the API, and you can create a chart by creating an instance of the appropriate class. For example, to create a line chart, you can use the following code:

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
In this example, a new line chart is created and displayed in the HTML element with the ID ‘chart_div’.

Jay is a Software Engineer and Writer. He blogs occasionally at Code Handbook and Tech Illumination.

Angular TutorialsCharts
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week