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;
}
})
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;
}
})
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**
....
});
You can use native JS Array#forEach function as it gives you access the index of the object in the array.
I used id
assuming you are actually passing an id
in to the function to identify the object that needs to be deleted from the array. Looking at your code above, name
seems more ideal, if that's unique property in the object of course
$scope.file.forEach(function(file, index){
if (file.id === id){ // Where id is your identifier, could be file.name === name.
this.splice(index, 1);
}
});