0

The multiple uploading of files works well with angularjs, but i can't get the file name inside my .then() function .

This is my uploading files function :

    $scope.uploadFile = function(files,destinationPhp) {

    $scope.montrerLoader = true;

    for (var x=0;x<files.length;x++){

        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[x]);

        console.log(files[x].name);
        var uploadUrl = destinationPhp;

        $http.post(uploadUrl, fd, {
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).then(function(data){ 
            $scope.montrerLoader = false;
            if(data.data.reponse=='ok'){

                if(destinationPhp=='uploadFichier.php'){
                    Notification.success('Fichier transféré!');
                    $scope.rendezVous.fichiers.push({'nom':files[x].name});
                }
            }
            else{

                Notification.error(data.data.reponse);
            }

        });

    }

};

It works well, the files get uploaded to my server directory, but the problem is this line that i need !:

$scope.rendezVous.fichiers.push({'nom':files[x].name});

I 've got this error :

TypeError: files[x] is undefined

I've tried plenty of thins, like trying to put the filename into a TEMP var, it is never recognized, or eventually always push the same namefile ( it is not logic).

Have you got any idea on how to push my files names after uploading into $scope.rendezVous ?

The iller is that this line :

 console.log(files[x].name);

Show the rights files names inside my firebug console !! but as long asI try to use in inside .then(), then it doesnt work !

1 Answers1

0

You're attempting Async call inside for loop, so you've to use IIFE. So, enclosing $http inside IIFE will let it run on every value of i of for loop & the files object will not be undefined in its callback. Check this Sample

for (var index = 1; index <= files.length; index++) {      
    (function(index) {
        $timeout(function() { 
        console.log("index : "+index); 

         alert("file name : "+files[index-1].name);
        }, index * 500);
    })(index);
}

http://plnkr.co/edit/7ZclGB93Soq5Ce8pFmkQ?p=preview

Here I've added mock async call using $timeout, & then used it inside for loop with IIFE structure. You can check your condition reproducing just when you comment out the IIFE wrapper for that async call.

Shantanu
  • 3,483
  • 2
  • 17
  • 20