Skip to content

Instantly share code, notes, and snippets.

@benmj
Created February 27, 2013 23:33
Show Gist options
  • Save benmj/5052868 to your computer and use it in GitHub Desktop.
Save benmj/5052868 to your computer and use it in GitHub Desktop.
An AngularJS Directive for creating a table using the Google Visualization API
/*
I'm converting an existing web-app to angular. We made extensive use of the
Google Visualization library in the past. It's a powerful, although
complicated API, so I was anxious to get it wrapped up in angular. This
populates a table with data returned from a custome service 'Account'
*/
'use strict';
/* Directives */
(function () {
var app = angular.module('googleVisualization.directives', []);
app.directive('googleTable', ['$parse', function($parse) {
var tableEvents = 'select page sort ready';
return function(scope, element, attrs) {
scope.$watch(attrs.table, function(value) {
if(!value)
return;
var options = angular.extend({}, scope.$eval(attrs.options));
var table = new google.visualization.Table(element[0]);
var data = new google.visualization.DataTable(value.data);
var view = new google.visualization.DataView(data);
table.draw(view, options);
var model = $parse(attrs.model);
//Set scope variable for the map
model.assign(scope, {
'table' : table,
'data' : data,
'view' : view,
});
bindTableEvents(scope, tableEvents, table, element);
});
};
}]);
// inspired by angular-ui's directive for google maps
function bindTableEvents(scope, eventsStr, googleObject, element) {
angular.forEach(eventsStr.split(' '), function (eventName) {
var $event = { type: 'table-' + eventName };
google.visualization.events.addListener(googleObject, eventName, function (evt) {
element.triggerHandler(angular.extend({}, $event, evt));
//We create an $apply if it isn't happening. we need better support for this
//We don't want to use timeout because tons of these events fire at once,
//and we only need one $apply
if (!scope.$$phase)
scope.$apply();
});
});
}
})();
/* Controller */
angular.module('myApp').controller('TableTestCtrl', function ($scope, Account) {
$scope.tableModel = {};
$scope.tableOptions = {
allowHTML: true,
showRowNumber: true
};
$scope.account = Account.get({accountID : 2}, function(account) {
// placeholder
});
$scope.$watch('tableModel', function() {
if (!$.isEmptyObject($scope.tableModel)) {
console.log('table initialized');
}
});
$scope.tableSelect = function(e) {
console.log('Table select in main');
};
$scope.tableSort = function(e) {
console.log('table sort in main');
};
});
/* Template */
<div google-table
table="account.Summary"
model="tableModel"
options="tableOptions"
ui-event="{ 'table-select': 'tableSelect(e)', 'table-sort' : 'tableSort(e)' }">
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment