0

when I get the result from my http request , I want to modify a scope . To test, I tried to display the scope before making the http request and after its success :

$scope.CopyFiles=function(destination){
  for(var i=0; i<$scope.list.length; i++){
    console.log("test 1 "+$scope.list[i]);

    var response=$http({method: 'GET', url:      
             '/checkIsSubdir/'+$scope.list[i]+'/'+destination});

    response.success(function(result) {
      console.log("check"+result.data);
      console.log("test 2 "+$scope.list[i]);
    });
    response.error(function(data, status, headers, config) {
      console.log("checksubdir oops");
    });
  };

my http request has succeded since it displayed my result.data.

my problem is that the first console.log("test 1 "+$scope.list[i]); displays the scope but console.log("test 2 "+$scope.list[i]); displays undefined

how to do to fix this ?

Yuri
  • 447
  • 3
  • 9
  • 19

1 Answers1

1

Simply your code is executing asynchronously inside a for loop.

That is because your for loop makes an ajax call & end when the value doesn't satisfied for loop condition at that time the value of i would be +1 than $scope.list.length, so thats why you are getting $scope.list[i] value undefined.

In this case use of angular.forEach would solve your problem, here the index value is available at that for loop success

angular.forEach($scope.list, function(value, index){
    console.log("test 1 "+$scope.list[index]);

    var response=$http({method: 'GET', url:      
             '/checkIsSubdir/'+$scope.list[index]+'/'+destination});

    response.success(function(result) {
      console.log("check"+result.data);
      console.log("test 2 "+$scope.list[index]);
    });
    response.error(function(data, status, headers, config) {
      console.log("checksubdir oops");
    });
});
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299