如何在angularjs中使用输入[type=file]验证表单

How to validate form with input[type=file] in angularjs

本文关键字:type file 表单 验证 输入 angularjs      更新时间:2023-09-26

HTML:

<form name="form">
    <input type="file" ng-model="document" valid-file required>
    <input type="submit" value="{{ !form.$valid && 'invalid' || 'valid' }}">
</form>

用于侦听输入[type=file]更改的自定义指令:

myApp.directive('validFile',function(){
    return {
        require:'ngModel',
        link:function(scope,el,attrs,ngModel){
            //change event is fired when file is selected
            el.bind('change',function(){
                 scope.$apply(function(){
                     ngModel.$setViewValue(el.val());
                     ngModel.$render();
                 });
            });
        }
    };
});

当选择文件时,控制台中出现以下错误:

错误:InvalidStateError:DOM异常11错误:尝试使用不可用或不再可用的对象。

试试plunkr:http://plnkr.co/edit/C5j5e0JyMjt9vUopLDHc?p=preview

如果没有该指令,输入文件字段的状态将不会被推送到表单。$valid。你知道我为什么会出现这个错误以及如何解决这个问题吗?

来自NgModelController的引用$render()

在需要更新视图时调用预计ng模型指令的用户将实现此方法

你需要实现$render()来调用它

myApp.directive('validFile', function () {
    return {
        require: 'ngModel',
        link: function (scope, el, attrs, ngModel) {
            ngModel.$render = function () {
                ngModel.$setViewValue(el.val());
            };
            el.bind('change', function () {
                scope.$apply(function () {
                    ngModel.$render();
                });
            });
        }
    };
});

DEMO

更新到AngularJS 1.2.x后,代码段看起来不再正常工作,并且文件输入与所选文件值不一致,导致表单不可用。将指令更改回原来的指令,并删除ngModel.$render(),它看起来像一个魅力:

.directive('validFile', function () {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function (scope, el, attrs, ngModel) {
      el.bind('change', function () {
        scope.$apply(function () {
          ngModel.$setViewValue(el.val());
        });
      });
    }
  };