Adding and Handling Click Events for NVD3 Graph Elements in Angular Applications

1 Comment

Larry Van Sickleby Larry Van Sickle, Senior Software Engineer

NVD3 is an easy-to-use JavaScript library for building charts and graphs. Very often designers want to have a chart be interactive, letting user drill down on data by clicking on elements of the charts. For example, on a bar chart of votes by state, the user could click on the bar for Texas and see a new chart with the votes by region for the state.

AngularJS is a versatile toolset for building browser-based applications.

How can a developer make the elements of a chart clickable using NVD3 in an Angular application?

There are lots of ways to incorporate and use NVD3 in your JavaScript application.   We found that the Angular-nvD3 directive is an easy way to use NVD3 in an Angular application.   Using NVD3, it is simple to define the chart and provide the data as JSON objects.

The first step is to install NVD3 and Angular-nvD3.   Installation steps are clearly defined at the Angular-nvD3 website.

In HTML use an <nvd3> element to invoke the nvd3 directive where you want the graph to appear:
Code example

NVD3 has many different types of charts. We will work with a multi-bar horizontal bar chart. In the Angular controller set up the chart options and data that are passed to the directive:

angular.module('exampleApp')
    .controller('exampleCtrl', function($scope) {
        $scope.options = {
            chart: {
                type: 'multiBarHorizontalChart',
                height: 450,
                x: function(d){ return d.label; },
                y: function(d){ return d.value; },
                showControls: true,
                showValues: true,
                duration: 500,
                xAxis: {
                    showMaxMin: false
                },
                yAxis: {
                    axisLabel: 'Values',
                    tickFormat: function(d) {
                        return d3.format(',.2f')(d);
                    }
                }
            }
        };
        $scope.data = [
            {
                'key': 'Series1',
                'color': '#004433',
                'values': [
                    { 'label' : 'Group A' , 'value' : 3 } ,
                    { 'label' : 'Group B' , 'value' : 7 } ,
                    { 'label' : 'Group C' , 'value' : 5 }
                ]
            }
        ];
});

Now add a handler for click events on the bars of the graph.   This is the “secret ingredient” that is difficult to find.   We need to add a callback property to the $scope.options object. The added code is in bold red font below:

$scope.options = {
    chart: {
        type: 'multiBarHorizontalChart',
        height: 450,
        x: function(d){return d.label;},
        y: function(d){return d.value;},
        showControls: true,
        showValues: true,
        duration: 500,
        xAxis: {
            showMaxMin: false
        },
        yAxis: {
            axisLabel: 'Values',
            tickFormat: function(d) {
                return d3.format(',.2f')(d);
            }
        },
        callback: function(chart) {
            chart.multibar.dispatch.on('elementClick', function(e){
                console.log('elementClick in callback', e.data);                             
            });
        }
    }
};

The anonymous function we have added is executed when the user clicks on a bar in the bar chart. The function gets an event argument that includes the data associated with the bar that was clicked.   In a real application instead of issuing a console log message, the function could examine the data for the bar that was clicked and change the display based on that data.

Using NVD3 and Angular and this technique will let you build graphic applications with very natural and intuitive user interfaces.

Author: bridge360blog

Software Changes Everything.... Bridge360 improves and develops custom application software. We specialize in solving complex problems at every phase of the software development lifecycle, removing roadblocks to help our clients’ software and applications reach their full potential in any market. The Bridge360 customer base includes software companies and world technology leaders, leading system integrators, federal and state government agencies, and small to enterprise businesses across the globe. Clients spanning industries from legal to healthcare, automotive to energy, and high tech to high fashion count on us to clear a path for success. Bridge360 was founded in 2001 (as Austin Test) and is headquartered in Austin, Texas with offices in Beijing, China.

One thought on “Adding and Handling Click Events for NVD3 Graph Elements in Angular Applications

  1. Thanks Larry. Made sense and it worked. What more could you ask for?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s