如何验证与angularjs输入[type = file]形式 [英] How to validate form with input[type=file] in angularjs

查看:138
本文介绍了如何验证与angularjs输入[type = file]形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML

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

自定义指令来监听输入[type = file]的变化:

Custom directive to listen for input[type=file] changes:

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

当选定文件下面的错误出现在控制台:

When file is selected following error appears in console:

错误:InvalidStateError:DOM异常11错误:试图
  使用一个对象,它是不是或不再,可用的。

Error: InvalidStateError: DOM Exception 11 Error: An attempt was made to use an object that is not, or is no longer, usable.

试着用plunkr:<一href=\"http://plnkr.co/edit/C5j5e0JyMjt9vUopLDHc?p=$p$pview\">http://plnkr.co/edit/C5j5e0JyMjt9vUopLDHc?p=$p$pview

如果没有指令输入文件场的状态不会被推向形成$有效。任何想法,为什么我得到这个错误,以及如何解决这一问题?

Without the directive the the state of the input file field wont be pushed to form.$valid. Any ideas why I get this error and how to fix this?

推荐答案

从<一个参考href=\"http://docs.angularjs.org/api/ng.directive%3angModel.NgModelController\">NgModelController.$render()

当视图需要更新调用。 据预计,
  在NG-模型指令的用户将实现此方法。

Called when the view needs to be updated. It is expected that the user of the ng-model directive will implement this method.

您需要实现$渲染()调用它。你可以做这样的事情。

You need to implement $render() to call it. You can do something like this

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

<大骨节病> 演示

这篇关于如何验证与angularjs输入[type = file]形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆