【问题标题】:Angular js change 'file' type to 'text' type [Safari]Angular js 将“文件”类型更改为“文本”类型 [Safari]
【发布时间】:2017-02-26 22:53:01
【问题描述】:

我有从数组中的对象构建的输入。

一切正常,但是当input.type = 'file',Angular 将其更改为 文本类型,我无法弄清楚。

有没有注意到这一点?

我的模板:

<span ng-repeat="input in formInputs">
    <label for="{{input.id}}">{{input.label}}</label>
    <input type="{{input.type}}" id="{{input.id}}" name="{{input.name}}" ng-model="input.insert" ng-required="input.must">
</span>

我的数组:

var formInputs = [
    {
        label     : 'first name',
        id        : 'id1',
        type      : 'text',
        name      : 'name1',
        must      : true,
        insert    : ''
    },
    {
        label     : 'upload file',
        id        : 'id2',
        type      : 'file',
        name      : 'name2',
        must      : true,
        insert    : ''
    }
]

我的结果:

<span ng-repeat="input in formInputs">
  <label for="id1">first name</label>
  <input type="text" id="id1" name="name1" ng-model="input.insert" ng-required="input.must">
  <label for="id2">upload file</label>
  <input type="text" id="id2" name="name2" ng-model="input.insert" ng-required="input.must">
</span>

编辑:

我有这个流动:

<input type="{{childInput.type}}" id="{{childInput.id}}" name="{{childInput.name}}">

还有这个数组:

var formInputs = [
    {
        id        : 'id',
        type      : 'file',
        name      : 'name',
    }
]

坚决[仅在 Safari 中]:

<input type="text" id="id" name="name">

为什么会这样?

感谢您的帮助!

【问题讨论】:

标签: javascript angularjs html forms


【解决方案1】:

来自AngularJS Documentation for input

注意:并非所有提供的功能都适用于所有输入类型。具体来说,input[file] 不支持通过ng-model 进行的数据绑定和事件处理。

所以看起来 Angular 回到了type="text"。有很多答案可以解决这个问题,请查看:

从那个答案来看,这是一种处理文件输入的方法。

.directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                    });
                }
                reader.readAsDataURL(changeEvent.target.files[0]);
            });
        }
    }
}]);

正如Hackerman 所提到的,他的jsfiddle 乍一看似乎可以工作(使用Angular 1.0.1),但它似乎无法正确填充模型。

【讨论】:

  • 我的对象中有一个动态类型,我所需要的只是我的对象类型插入到我的模板中的输入类型中。为什么将“文件”字符串更改为“文本”?抱歉,我没听懂。
  • @ZeevKatz 因为ng-model 不支持文件输入,它看起来像是回退到文本输入。
  • 好的,我从输入中删除了 ng-model,但它不起作用。我正在编辑我的问题。
  • 它只发生在野生动物园!
  • @ZeevKatz 哦,很抱歉造成误解,我刚刚看到您问题中的编辑。我没有 Safari,因此测试它会很困难,而且我无法轻松提供进一步的帮助。
猜你喜欢
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2014-02-13
  • 2020-06-22
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多