Total Pageviews

2015/09/02

[AngularJS] How to clear file input

Problem
After I select file and click reset button, but the file input value does not be cleared as expected.



Code snippet in HTML
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<div class="row">
    <div class="col-sm-12">
        <div class="col-sm-6 ">
            <label class="control-label label-width-4 text-right">選擇檔案</label>
            <input id="attachment" name="attachment" type="file" class="form-control" 
                   data-ng-file-select="onSelect($files)" data-ng-model="attachment" 
                   style="width: 60%;">
        </div>
        <div class="col-sm-6 "></div>
    </div>
</div>


Code snippet in JavaScript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
 $scope.onSelect = function($files) {
     $scope.attachment = $files[0].name;
     $scope.files = $files;
 };
 
 $scope.resetForm = function(){
    cAlerter.clear();
    
    $scope.dbm002eFormBean.impType = "";
    $scope.findImpTypes();
    $scope.dbm002eFormBean= $scope.dbm002eFormBean || {};
    $scope.dbm002eFormBean.updType = "0";
    
    $scope.attachment = null;
    $scope.files = null;               
 };


Solution
update resetForm Function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
 $scope.resetForm = function(){
    cAlerter.clear();
    
    $scope.dbm002eFormBean.impType = "";
    $scope.findImpTypes();
    $scope.dbm002eFormBean= $scope.dbm002eFormBean || {};
    $scope.dbm002eFormBean.updType = "0";
    
    $scope.files = null;
    
    //find all file input and set value to null
    angular.forEach(
      angular.element("input[type='file']"),
         function(inputElem) {
           angular.element(inputElem).val(null);
    });
 };



Reference
[1] http://stackoverflow.com/questions/15079779/how-to-clear-a-file-input-from-angular-js

No comments: