【问题标题】:How to validate form with input[type=file] in angularjs如何在 angularjs 中使用 input[type=file] 验证表单
【发布时间】:2013-08-22 14:34:18
【问题描述】:

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

如果没有该指令,输入文件字段的状态将不会被推送到 form.$valid。任何想法为什么我会收到此错误以及如何解决此问题?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    来自NgModelController.$render()的参考

    当视图需要更新时调用。 预计 ng-model 指令的用户将实现此方法。

    你需要实现 $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

    【讨论】:

    • 是否可以在渲染器中获取文件大小?例如检查已选择文件的 mimetype 或大小 ...
    【解决方案2】:

    更新到 AngularJS 1.2.x 后,sn-p 看起来不再正常工作,并且文件输入与所选文件值不一致,导致表单无法使用。 将指令改回原来的指令,并删除 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());
            });
          });
        }
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      • 2015-06-28
      • 2011-10-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多