Web Programming examples

Google Maps,AngularJS

Google Chart 2-way data binding

  • AngularJS : 1.6.5
  • Bootstrap : 3.x
  <head>
//
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  </head>
  <body>
    <div ng-controller="MyCtrl">
      <div g-chart></div>
      <select id="chartType" ng-model="chartType"
              ng-change="selectType(chartType)" 
              ng-options="c.typeName for c in chartTypes">
      </select>
    </div>
    <script type='text/javascript' src='js/angular.min.js'></script>
    <script type="text/javascript" src="js/app.js"></script>
  </body>
google.charts.load('current', {packages: ['corechart']});

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

var mymodule=angular.module('myApp', [])

mymodule.controller('MyCtrl', ['$scope',
  function($scope) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Topping');
    data.addColumn('number', 'Slices');
    data.addRows([
      ['Mushrooms', 3],
      ['Onions', 1],
      ['Olives', 1],
      ['Zucchini', 1],
      ['Pepperoni', 2]
    ]);
    var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300};
    var chart = {};

    chart.data = data;
    chart.options = options;

    $scope.chartTypes = [
      {typeName: 'LineChart', typeValue: '1'},
      {typeName: 'BarChart', typeValue: '2'},
      {typeName: 'ColumnChart', typeValue: '3'},
      {typeName: 'PieChart', typeValue: '4'}
    ];
    $scope.chartType = $scope.chartTypes[0];

    $scope.selectType = function(type) {
      $scope.chart.type = type.typeValue;
    }
    chart.type = $scope.chartTypes[0].typeValue;

    $scope.chart = chart;
  }
]);

mymodule.directive('gChart', function() {
  return {
    restrict: 'A',
    link: function($scope, elm, attrs) {
      $scope.$watch('chart', function() {
        var type = $scope.chart.type;
        var chart = '';

        if (type == '1') {
          chart = new google.visualization.LineChart(elm[0]);
        } else if (type == '2') {
          chart = new google.visualization.BarChart(elm[0]);
        } else if (type == '3') {
          chart = new google.visualization.ColumnChart(elm[0]);
        } else if (type == '4') {
          chart = new google.visualization.PieChart(elm[0]);
        }

        chart.draw($scope.chart.data, $scope.chart.options);
      },true);
    }
  };
});

One thought on “Google Chart 2-way data binding”

  1. Excellent post. Keep writing such kind of information on your blog.

    Im really impressed by your site.
    Hi there, You’ve done a fantastic job. I’ll definitely digg it and in my opinion recommend to
    my friends. I’m confident they will be benefited from this site.

Comments are closed.