Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to splice selected element from FileList

here is my multipart form selected files

selected files preview with fileReader in javascript

if i remove from previewed image. it must delete from selected files!

$scope.getFile = function () {
    $scope.progress = 0;
    $scope.variant.images = [];
    var files = $scope.file;
    for ( var i = 0; i < files.length; i++) {
        var file = files[i];
        fileReader.readAsDataUrl(file, $scope).then(function(result) {
            $scope.variant.images.push({path: result})


        });
    }
};

i try like this but it does not works

angular.forEach($scope.file, function (value, key) {
        if(key === id){
            delete value;
        }
    })
like image 949
Bilegsaikhan Avatar asked Sep 01 '25 22:09

Bilegsaikhan


1 Answers

You cannot splice a FileList. It is readonly! It only has the length and item but no array logic like splice', 'split., etc. So you will have to make a copy from it in an array:

// **A**
$scope.fileArray = [];
angular.forEach($scope.file, function(file) {
    $scope.fileArray.push(file)
});

And then you can splice from this array with something like:

$scope.deleteImage = function(index) {
   $scope.fileArray.splice(index, 1);
})

As you mention 'preview' I guess you are displaying a thumbnail of the selected images. You will have to change any display logic also to use the fileArray instead of the current file. So it automatically updates when the user removes one element.

<div ng-repeat="image in fileArray"... >

So best to set up an angular watch to recalculate $scope.fileArray as given above. However I'm afraid you cannot do a $watch on a file list. Not certain, but I recently found out that Angular does NOT support ng-model on a <input type="file". I found a solution for this in this article.

So if a simple $scope.$watch('file', function.. doesn't work, you'd best import use the fileModel directive in that into your system and enhance the file-input in your view with it:

<input type="file" name="files" file-model="filesArray" multiple accept="image"/>

You should then be able to watch that filesArray you assign to it:

$scope.$watch('fileArray', function() {
    // Code from **A**
    ....
});
like image 51
Bart Avatar answered Sep 03 '25 10:09

Bart