0

Following is the code, which is consoling the response but unable to set the response to store in $scope.dateWiseData array. Let me know what I am doing wrong.

$scope.dateWiseData = [];
var tmpArr = [];
var x = 0;
for (var i=0; i< 7;i++) {
    $http.post('/api/getdata', {_id: currentUser._id, data: data}).then(function(response){
        console.log(response.data);
        tmpArr.push(response);
        if ( x < 7 ) {
            $scope.dateWiseData = tmpArr;
        }
        x++;
    });
}
console.log("--Week Data Array--");
console.log($scope.dateWiseData);
1
  • I would create an array of promises, 6 in your case, and use $q.all instead. What you posted looks fine, but the problem is when will you be able to tell it's all been finished? Commented Sep 24, 2014 at 6:26

1 Answer 1

1

if you try to print the console.log($scope.dateWiseData); this will execute before the $scope.dateWiseData array is assigned to data which means this will print before the data is getting from server. but your data should be assigned to that array after the http is completes. You need to check the promises in javascript

$scope.getData() = function(){
    var deferred = $q.defer();
    for (var i=0; i< 7;i++) {
        $http.post('/api/dayavailability', {_id: SessionService.currentUser._id, weekDay: new Date($scope.sevenWeekDayArr[i]).toISOString()}).then(function(response){
            tmpArr = response.data;
            if ( x < 7 ) {
                $scope.dateWiseData.push(tmpArr);
            }
            if(x==6) {
                deferred.resolve();
            }
            x++;
        });
    }
    return deferred.promise;
}

wrapt that for loop like this and

$scope.getData().then(function() {
   // processing
});

** Dont forget to add $q in as a parameter in the controller **

Sign up to request clarification or add additional context in comments.

5 Comments

yes {{dateWiseData}} use this in the view and u can print the values on the page
ok..data is populating in the view but what if I need to use the $scope.dateWiseData later in my controller, how do I do this ?
didnt get that. could u please describe a bit :)
post your full angular controller

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.