2017-08-10 83 views
-1

上載文件後,表格不清晰。如何在angularjs中上傳s3桶中的文件後清除表單輸入?

<div class="aboutFile"> 
    <input type="file" name="file" fileread="vm.file" class="form-control" ng-model="vm.file"> 
     <div class="create-component--perma-bg"> 
      <i class="fa fa-plus-square-o" aria-hidden="true"></i> 
      <span ng-if="!vm.file.name">Add File </span> 
      <span ng-if="vm.file.name">{{vm.file.name}}</span> 
     </div> 
      <button type="button" class="btn btn-info bgChangeBtnInfo" ng- 
      click="vm.upload(vm.file)" ng-disabled="!vm.file"> Upload</button> 
     </div> 

vm.upload方法調用。

vm.upload = (fileObj) =>{ 
     vm.call("saveSlideFile", vm.slideObject, (error, result) => { 
      if (!error) { 
      vm.file={}; 
      console.log('File saved successfully'); 
      } 
     }) 
    } 

fileread指令

angular.module('livePoll') 
    .directive("fileread", [function() { 
     return { 
      scope: { 
       fileread: "=" 
      }, 
      link: function(scope,element, attributes){ 
       $('.button-collapse').sideNav(); 
       element.bind("change", function (event) { 
        scope.$apply(function() { 
         scope.fileread = event.target.files[0]; 
         scope.$parent.fileread = scope.fileread; 
        }); 
       }) 
      }}; 
    }] 
+1

你的指令改變只在'change'事件模型,但不清除該字段時從父控制器模型的變化。看看[這個答案和可能的指令實現](https://stackoverflow.com/a/44517492/4222181)。 –

回答

0

我解決了這個問題,只是一個驚人的技術網站的幫助下,即的代碼行3210。感謝球員的幫助,我會與大家分享這個信息。

只要按照下述步驟: -

在輸入形式,我們必須分配的ID。

<input type="file" name="file" fileread="vm.file" class="form-control" id="inputFile" ng-model="vm.file"> 

在該凡vm.upload方法被稱爲有我用$('#inputFile').val('');用於執行任何動作之後清除表單字段。

vm.upload

vm.upload = (fileObj) =>{ 
    vm.call("saveSlideFile", vm.slideObject, (error, result) => { 
     if (!error) { 
     $('#inputFile') 
     vm.file={}; 
     console.log('File saved successfully'); 
     } 
    }) 
} 
+0

在控制器中操作DOM [這不是一個好的做法](https://stackoverflow.com/questions/29981419/angularjs-why-manipulating-dom-in-controller-is-a-bad-thing)。爲什麼不在'directive'中做這個? –

+0

感謝您分享。我會更新它 –

2

1)避免使用scope.$parent.fileread = scope.fileread;code smells,因爲你正在使用=綁定沒有任何意義,並可能導致不可預知的行爲。

2)如果你正在使用ngModel,就可以避免在你的指令使用綁定和使用NgModelController.$setViewValue更新的觀點一樣,值:

function onChange (event) { 
    //update bindings in $apply block 
    $scope.$apply(function(){ 
    ngModel.$setViewValue(event.target.files[0]); 
    }); 
} 
//change event handler 
element.on('change', onChange); 

3)您可以在NgModelController.$viewValue建立一個$watch裏面你指令並清除輸入字段,當值在父改爲:

//set up a $watch for the ngModel.$viewValue 
$scope.$watch(function() { 
    return ngModel.$viewValue; 
}, function (value) { 
    //clear input value if model was cleared 
    if (!value) { 
    element.val(""); 
    } 
});