0

以下html用于选择一些图片进行上传

<input type="file" id="files" ngf-select="select(files)" ng-model="files" name="file" accept="image/*" ngf-max-size="'2MB'" required ngf-multiple="true">   

我正在使用以下 html 将所选图像显示为缩略图,并带有一个按钮以在上传之前取消所选文件。

<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>

单击取消按钮时在控制器中:

$scope.cancelPic = function(index) {

        $scope.files[index] = undefined;

        //$scope.files.length--;
      }

这可以删除选定的图像及其取消按钮(通过 ng-show)。问题是什么时候上传文件,这里是上传功能

$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);

          }
        }
      }]);

有以下错误:

TypeError: Cannot set property 'progress' of undefined
    at userCtrl.js:58

这是有错误的行:

$scope.files[index].progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));

cancelPic 函数不会更改索引值,如果选择了 3 个文件并使用 cancelPic 删除了一个文件,则索引的值仍为 3。我添加了一行来减少 files.length 为:

$scope.files.length--;

哪个确实将索引减少到 2,但我仍然像以前一样收到错误,并且当使用 cancelPic 删除一个文件时,从所选文件中删除了两个?我对那个有点不解。

我认为 cancelPic 函数的逻辑是错误的。

4

1 回答 1

0

要从数组中删除索引,您应该使用splice函数。所以这应该为你解决它:

$scope.cancelPic = function(index) {
   $scope.files.splice(index,1);
   $scope.files = $scope.files.slice(0);    
}

第二行是更改$scope.files对象值,以便 angular 触发验证。仅使用第一行不会触发$scope.$watch('files')

于 2015-09-23T05:42:41.113 回答