AngularJS 1 Onsen app and Google Charts
-
How do we load, initialize and use Google Charts successfully in an AngularJS 1 Onsen app?
According to its Quick Start, we need to:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> // Load the Visualization API and the corechart package. google.charts.load('current', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.charts.setOnLoadCallback(drawChart); // Callback that creates and populates a data table, // instantiates the pie chart, passes in the data and // draws it. function drawChart() { ... blah blah blah ... } </script>
Now suppose my Onsen app is as follows:
ons.bootstrap() .controller('AppController', function($scope) { this.drawChart = function(){ ... blah blah blah ... }; ons.ready(function() { // Load the Visualization API and the corechart package. google.charts.load('current', {'packages':['corechart']}); // Set a callback to run when the Google Visualization API is loaded. google.charts.setOnLoadCallback(this.drawChart); // Error: "this.drawChart" is null. }; });
Currently, my
ons.ready
cannot find thethis.drawChart
function in the controller.
-
@wetfeet You know this typical question in JavaScript… What is this? Your function inside
ons.ready
is creating a new scope. (function() {...}.bind(this)
) You have to bindthis
to the function if you want it to have the same scope. Otherwise, use a variable instead ofthis
.