The following html is used to select some images for upload
<input type="file" id="files" ngf-select="select(files)" ng-model="files" name="file" accept="image/*" ngf-max-size="'2MB'" required ngf-multiple="true">
I am using the following html to display selected images as thumbnails with a button to cancel the selected file prior to uploading them.
<div ng-repeat="f in files track by $index">
<div ng-show="f.type.indexOf('image') > -1">
<img ngf-src="f" class="thumb">
<button class= "btn btn-warning btn-cancel" ng-disabled="!myForm.$valid"
ng-click="cancelPic($index)">Cancel</button>
<br><br>
<p>{{f.name}}</p>
<br>
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%"
ng-bind="f.progress + '%'"></div>
</span>
<hr>
</div>
</div>
In the controller when the cancel button is clicked:
$scope.cancelPic = function(index) {
$scope.files[index] = undefined;
//$scope.files.length--;
}
This works to remove the selected image and its cancel button (via ng-show). The problem is when then the file is uploaded, here is the upload function
$scope.uploadPic = function(files) {
for(var i = 0; i < $scope.files.length; i++) {
var $file = $scope.files[i];
(function(index) {
$scope.upload[index] = Upload.upload({
url: '/',
method: 'POST',
file: $file,
}).progress(function (evt) {
//error here
$scope.files[index].progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
}).then(function (response) {
$timeout(function () {
$file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
})(i);
}
}
}]);
There is the following error:
TypeError: Cannot set property 'progress' of undefined
at userCtrl.js:58
This is the line with the error:
$scope.files[index].progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
The cancelPic function doesn't change the index value which if 3 files were selected and one was removed with cancelPic the value of index is still 3. I added a line to decrement the files.length as:
$scope.files.length--;
Which does reduce the index to 2 but I still get the error as before plus when one file is removed with cancelPic two are removed from the selected files? I am not a little puzzled by that one.
The logic of the cancelPic function is faulty I think.
To remove an index from an array you should use
splice
function. So this should fix it for you:The second line is to change
$scope.files
object value so that validations would be triggered by angular. Just using the first line will not trigger$scope.$watch('files')
.