ng-file-upload(在单文件选择,并且通过点击“上传”按钮上传文件的情况下,如何在真正选择文件之前保留上一文件信息?)

 文章前面研究ng-file-upload可能涉及指令:

You can use ng-model or ngf-change instead of specifying function for ngf-drop and ngf-select

ngf-change

"点击"、"取消"按钮不触发该事件,双击文件进行选择才触发

ng-before-model-change="beforeChange($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event)"

"点击"、"取消"按钮不触发该事件,双击文件进行选择才触发

ngf-keep(针对ngf-multiple="true" 多文件上传情况)

false: 默认状态

true: 保留上一次的文件信息基础上,追加新的文件信息

distinct: 去除files中重复的文件

ng-model

值为单文件而不是数组文件的条件:

1) ngf-multiple未设置或者设置为false

2) 元素上未设置multiple属性

3) ngf-keep未设置或者为false

综上条件:即为单文件上传情况,ng-model的值为单文件信息数据

 问题追踪思路:

<button class="btn btn-info" ngf-select ng-model="standardFile" accept=".txt" ngf-max-height="1000" type="file" ng-disabled="standardFile.uploading">选择自定义词典文件</button>

ng-change 代替ng-model

<button class="btn btn-info" ngf-select ngf-change="standardFileChange($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event)" accept=".txt" ngf-max-height="1000" type="file" ng-disabled="standardFile.uploading">选择自定义词典文件</button>
$scope.standardFileChange = function($files, $file, $newFiles, $duplicateFiles, $invalidFiles, $event) {
            console.log($files,$file,$newFiles, $duplicateFiles, $invalidFiles, $event);
            if ($newFiles[0]) {
                $scope.standardFile = $newFiles[0];
            }
        };

上述解决方案可以实现点击选择文件按钮情况下不清楚之前文件信息,但是如果有移除按钮就会出现状况!

<td class="w10">
    <button class="btn btn-info" type="submit" ng-click="standardSubmit(standardFile)" ng-disabled="!standardFile||standardFile.uploading||standardFile.dicsLoading">上传</button>
</td>
<td class="w10">
     <button class="btn btn-danger" ng-click="removestandardFile()" ng-disabled="!standardFile||standardFile.uploading||standardFile.dicsLoading">移除</button>
</td>

$scope.removestandardFile = function() {
  delete $scope.standardFile;
};

因为

$scope.standardFile = $newFiles[0];数据双向绑定缘故导致变量出现问题!

继续问题的追踪

$scope.standardFile = angular.copy($newFiles[0]);

把双向绑定改为copy,然而发现打印出来并没有copy成功,再使用寻找到的自定义copy函数

function copy(obj) {
            var clone = {};
            for (var key in obj) {
                clone[key] = obj[key];
            }
            return clone;
  };

发现在传参的过程中,参数传的并不正确!

貌似要进行深度拷贝,继续寻找函数extendDeep函数

var extendDeep = function(dst) {
          angular.forEach(arguments, function(obj) {
            if (obj !== dst) {
              angular.forEach(obj, function(value, key) {
                if(angular.isObject(dst[key]) || angular.isArray(dst[key])){
                  extendDeep(dst[key], value);
                } else {
                  dst[key] = angular.copy(value);
                }     
              });   
            }
          });
          return dst;
};

重新试一遍,发现成功了!

$scope.standardFile = extendDeep($newFiles[0]);

果然是浅拷贝以及深拷贝的问题!!




原文地址:https://www.cnblogs.com/echo2016/p/5752121.html