LittleLebowski
LittleLebowski

Reputation: 7941

Converting JSON element into Javascript Array in AngularJS?

I'm using AngularJS to make a $resource call to GET some values in JSON format. My requirement is that I've a model element that needs a Javascript array of the form:

[
[1328983200000, 40],
[1328983200000, 33], 
[1328983200000, 25],
[1328983200000, 54],
[1328983200000, 26], 
[1328983200000, 25]
];

to be displayed in Flot charts. This information is contained in the JSON as follows:

{
"marks1":15,
"marks2":20,
"dailyMarks":{
"2013-02-27T07:25:35.000+0000":40,
"2013-03-01T07:25:35.000+0000":33,
"2013-02-26T07:25:35.000+0000":25,
"2013-02-23T07:25:35.000+0000":54,
"2013-03-03T10:12:59.000+0000":26,
"2013-03-02T07:12:59.000+0000":25},
}

where "dailyMarks" contain the elements I need. I can convert "dailyMarks" to Javascript array, but it doesn't seem to work: (Below is my Controller code)

function MyController($scope, $resource) {

    var User = $resource('/marks/fetch?from=:from&to=:to', {from: inStartDate, to: inEndDate}, {
        getAll: {method: 'GET', isArray: false}
    });

    $scope.changeDate = function(fromDate, toDate) {
        $scope.marks = User.getAll({from: fromDate, to: toDate});
    };
    var imarks = User.getAll();
    $scope.marks = imarks;

    var list = imarks.dailyMarks, arr = [];

    for (var key in list) {
        arr.push([+new Date(key), list[key]]);
    }

    $scope.myModel = arr;
};

What am I doing wrong? I get blank arr[] in the model. :( :( Kindly guide me.

Upvotes: 0

Views: 6366

Answers (1)

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

The problem here is that the $resource service is asynchronous even if its API might suggest that it is synchronous. This answer has more details regarding this topic: https://stackoverflow.com/a/11966512/1418796

What you should do is to move your array post-processing to a success callback of a call to the resource, something along those lines:

function MyController($scope, $resource) {

    var User = $resource('/marks/fetch?from=:from&to=:to', {from: inStartDate, to: inEndDate}, {
        getAll: {method: 'GET', isArray: false}
    });


    $scope.marks = User.getAll({from: fromDate, to: toDate}, function(marksFromServer){
      //post processing <-- goes HERE
    }
);
};

Other remark - you are constantly re-defining the User resource in a controller, you should rather move it to a factory and inject User to your controller.

Upvotes: 2

Related Questions