1

I have the problem with my script in html file. The problem is about updating variables by jQuery and then creating a chart from it.

I am using angular for chart creation so it is impossible to put it into different jQuery.

Part of the code:

var chartData = [];

            $.getJSON('../json/testData.json', function (json) {
                for (var i=0; i < json.length; i++){
                    var j = json[i].Value;
                    chartData.push(j);
                }
            });

angular.module("app", ["chart.js"]).controller("BarCtrl", function ($scope) {

            $scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
            $scope.series = ['Series A', 'Series B'];
            $scope.data = [
                [65, 59, 80, 81, 56, 55, 40],
                [28, 48, 40, 19, 86, 27, 90],
                chartData
            ];
        });

What I am trying to achieve: Get the data from JSON, update chartData, put updated variable into the chart.

How it works for now? -> It does everything, then jQuery, so I have empty array in the chart.

My Research: I was trying to manipulate the variable and the scope of the jQuery. The result is still the same. When I put everything into the function, angular doesn't work.

Solution from post below:

    angular.module("app", ["chart.js"]).controller("BarCtrl", function ($scope, $http) {

        $http.get('../json/testData.json').then(function (response) {
            for (var i = 0; i < response.data.length; i++) {
                var j = response.data[i].Value;
                jsondata.push(j);
            }
        });
Maltesse
  • 67
  • 1
  • 2
  • 8
  • Did you try moving the `angular.module` statement into the `$.getJSON` callback (right after the `for` loop? Or, move the `getJSON` into the `angular.module` callback. Both processes execute asynchronously, so you have to come up with a way for them to wait for each other. Max mentioned jQuery promises; that's a good choice. – Hari Lubovac Oct 05 '16 at 15:41
  • There are mix of asynchronous (getJSON) and synchronous code (the entire algorithm). Look at promises (but not jQuery promises) – Max Zuber Oct 05 '16 at 15:41

1 Answers1

1

Why don't you use $http service inside a controller to get data and then put it on the scope:

angular.module("app", ["chart.js"]).controller("BarCtrl", function ($scope, $http) {
    $scope.data = [];
    $http.get('../json/testData.json').then(function (response) {
        for (var i = 0; i < response.data.length; i++) {
            var j = response.data[i].Value;
            chartData.push(j);
        }
    });
});
Maltesse
  • 67
  • 1
  • 2
  • 8
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488