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

果然是淺拷貝以及深拷貝的問題!!

 

 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM