在 angularjs 中将文件上传到 s3 存储桶后如何清除表单输入?

How to clear form input after uploading file on s3 bucket in angularjs?

上传文件后表单不清晰。

  <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) 避免使用 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) 您可以在指令中设置一个 $watch on NgModelController.$viewValue 并清除输入字段,当值在父级中更改时:

//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("");
  }
});

在令人惊叹的技术网站 Technoalerts 的帮助下,我仅用一行代码就解决了这个问题。谢谢大家的帮助,我会和大家分享这个信息。

只需按照以下步骤操作即可:-

在输入表单中,我们必须分配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');
      }
   })
}