如何双向绑定到type="文件"用ng模型输入

How do I two-way bind to a type="file" input with ng-model?

本文关键字:quot 文件 ng 模型 输入 何双 type 绑定      更新时间:2023-09-26

基本上我想这样做:

<input type="file" ng-model="variable_in_scope">

当我选择一个文件时,variable_in_scope应该被分配给被选择的文件对象。此外,如果variable_in_scope的值在我的页面的其他地方被改变,它应该更新"选择文件"按钮旁边的文本,以表明所选择的文件已经改变。

对于任何其他类型的输入,这都可以工作。

我不需要做任何花哨的事情,比如实际看到文件的内容。最后,我想发布它,但我发现您可以通过将文件对象设置为FormData对象来实现这一点,而无需实际将内容读取到Javascript-land中。

我还发现了其他关于angular选择文件的问题,但是没有一个有双向绑定的解决方案。

我对另一个问题的回答提供了一种使用ng-model完成此操作的方法,但由于该问题不是专门关于双向绑定的(并且我的答案很难在那里找到),我将在这里复制它:

app.directive('bindFile', [function () {
    return {
        require: "ngModel",
        restrict: 'A',
        link: function ($scope, el, attrs, ngModel) {
            el.bind('change', function (event) {
                ngModel.$setViewValue(event.target.files[0]);
                $scope.$apply();
            });
            $scope.$watch(function () {
                return ngModel.$viewValue;
            }, function (value) {
                if (!value) {
                    el.val("");
                }
            });
        }
    };
}]);

要使用它,你只需要将它添加到你的angular模块中,并在你想要使用它的文件选择器中包含一个bind-file属性。

Angular不支持绑定到文件类型的输入,但我使用了许多其他答案拼凑了一个解决方案。

app.directive('filePicker', filePicker);
filePicker.$inject = ['$log', '$document'];
function filePicker($log,$document) {
  var directive = {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      ngModel: '='
    },
    link: _link
  };
  return directive;
  function _link(scope, elem, attrs, ngModel) {
    // check if valid input element
    if( elem[0].nodeName.toLowerCase() !== 'input' ) {
      $log.warn('filePicker:', 'The directive will work only for input element, actual element is a', elem[0].nodeName.toLowerCase());
      return;
    }
    // check if valid input type file
    if( attrs.type != 'file' ) {
      $log.warn('filePicker:', 'Expected input type file, received instead:', attrs.type, 'on element:', elem);
      return;
    }
    // listen for input change
    elem.on('change', function(e) {
      // get files
      var files = elem[0].files;
      // update model value
      scope.$apply(function() {
          attrs.multiple ? scope.ngModel = files : scope.ngModel = files[0];
      });
    });
    scope.$watch('ngModel', function() {
        if (!scope.ngModel)
            elem[0].value = ""; // clears all files; there's no way to remove only some
    });
  }
}

这个解决方案向我展示了如何使用指令来实现对ng-model的自定义绑定。它允许访问文件的内容,所以如果你需要这个功能,你可以把它添加到我的解决方案中。

但是,它的绑定有一些问题。它将正确设置我的variable_in_scope的值,但如果有其他东西绑定到variable_in_scope的值,它们将不会更新。诀窍是使用隔离作用域和$apply。那你就不用再插手$setViewValue的事了。设置好了就忘了它吧。

这让我知道了单向绑定。但是,如果我将值设置为variable_in_scope,那么文件选择器仍然显示我选中了原始文件。在我的例子中,我真正想做的就是清除选中的文件。我发现了Javascript魔法来做到这一点,并在ngModel上设置了$watch来触发它。

如果您想以编程方式将文件设置为不同的值,那么祝您好运,因为FileList是只读的。这个魔术可以让你清除FileList,但是你不能添加任何东西。也许你可以创建一个新的FileList并将其分配给.files,但粗略地看了一下,我没有看到这样做的方法。

help for me: FileUploader

用display: none隐藏输入元素;然后在输入元素的顶部使用一个标签,并将一个标签连接到作用域变量。看很多关于SO的帖子。这样的:

<label for="idFileUpload" class="custom-file-upload">
    SelectFile
</label>
<input type="file" id="idFileUpload" nv-file-select uploader="uploader">
<label id="idSelectedFile">{{selectedFile}}</label>
<md-button id="idUploadBtn" md-no-ink class="md-primary settingsBtns" ng-click="uploader.uploadAll()" ng-disabled="!uploader.getNotUploadedItems().length">Upload</md-button>
CSS:

input[type="file"] {
    display: none;
}
.custom-file-upload {
    background-color: green;
    color: white;
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

在FileUploader触发的事件中,您可以获取输入元素的值。HTH

相关文章: