'Initialize a json object to a variable

(function() {
   var app = angular.module('myApp', ['chartjs-directive']);

   app.controller('myController', function($scope,$http){
       var chart_data = {};

       $http.get('js/chart_data.json').success(function(data){
          chart_data = data;          
       });  

       $scope.myChart = {"data": chart_data, "options": {} };
   });

})(); 

If chart_data is directly assigned to key value pairs its working fine...

How to initialize chart_data variable inside $http service. The above syntax is not correct.



Solution 1:[1]

$http returns a promise, so you need to set the scope variable inside the callback:

$http.get('js/chart_data.json').success(function(data){
    $scope.myChart = {"data": data, "options": {} };
}); 

Solution 2:[2]

Your code won't work. We faced this issue many times.

We should take data after $http request. And no need of taking chart_data here

(function() {
   var app = angular.module('myApp', ['chartjs-directive']);

   app.controller('myController', function($scope,$http){
       $http.get('js/chart_data.json').success(function(data){
           $scope.myChart = {"data": data, "options": {} };
       });  

   });

})(); 

We can use $scope.myChart.data in html as myChart.data and in any part of controller

Solution 3:[3]

It should be like:-

(function() {
   var app = angular.module('myApp', ['chartjs-directive']);

   app.controller('myController', function($scope,$http){
       $scope.chart_data = {};

       $http.get('js/chart_data.json').success(function(data){
          $scope.chart_data = data;     
      $scope.myChart = {"data": $scope.chart_data, "options": {} };     
       });  


   });

})(); 

Solution 4:[4]

var chart_data = {}; this way you can initialize it as a an empty JSON obj.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 morsor
Solution 2 Veera Bhadra
Solution 3
Solution 4 Divya MV