-1
var    $scope.units = [1,2];
var  $scope.shiftplans = ['plan1','plan2','plan3']

         for(var i=0;i<$scope.units.length;i++){            
          for(var a=0;a<$scope.shiftplans.length;a++)  {
            console.log('i:'+i);
            console.log('a:'+a);
         } 
        }

prints :

i:0
a:0

i:0
a:1

i:0
a:2

i:1
a:0

i:1
a:1

i:1
a:2

but :

var    $scope.units = [1,2];
    var  $scope.shiftplans = ['plan1','plan2','plan3']

  for(var i=0;i<$scope.units.length;i++){            
     for(var a=0;a<$scope.shiftplans.length;a++)  {
       ***$http.get(function(){
               console.log('i:'+i);
               console.log('a:'+a);
       });***

     } 
 }

Console log in above ajax prints values in different values based on ajax response.

how to handle AJAX to complete and later to move to looping ?

Arun Kumar
  • 129
  • 1
  • 11

2 Answers2

0

You need to bound the value of i and a on a IIFE for each ajax call, because ajax calls are async, unlike the for-loop

example:

for(var i=0;i<$scope.units.length;i++){            
 for(var a=0;a<$scope.shiftplans.length;a++)  {
       (function(_i, _a) {
           ***$http.get(function(){
                 console.log('i:'+_i);
                 console.log('a:'+_a);
           });***
       })(i, a);
     } 
 }
Mohamed Shaaban
  • 1,129
  • 6
  • 13
0

As it is Asynchronous call, you can not handle when callback will be received AngularJs: $http Synchronous call

The only way I can think of how you can handle it is that you make an array of objects and map responses to be written to correct key. After all responses would be received it can print out the array. Something like this:

var $scope.units = [1,2];
var $scope.shiftplans = ['plan1','plan2','plan3'];

var sizeOfResponses = $scope.units.length * $scope.shiftplans.length;
var countOfResponses = 0;
var responsesArray = [];

for(var i=0;i<$scope.units.length;i++){            
  for(var a=0;a<$scope.shiftplans.length;a++)  {
    var index = i * $scope.units.length + a;
    responsesArray[index] = {i: null, a: null
    $http.get(function(){
      responsesArray[index].i = +i;
      responsesArray[index].a = +a;
      countOfResponses++;
      if(countOfResponses === sizeOfResponses)console.log(responsesArray);
   });

 } 

}

Community
  • 1
  • 1
Ricardas
  • 518
  • 6
  • 18