当前位置: 首页 > 面试题库 >

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

邢财
2023-03-14
问题内容

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。为什么我会收到此错误以及如何解决此问题的任何想法?


问题答案:

从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](http://plnkr.co/edit/yya3vMoaTFiONU9wrFVw?p=preview)**



 类似资料:
  • The file upload field is really hard to stylizing. The "Browse" button inaccessible to CSS manipulation. You can stylizing your input type='form' by this plugin. Idea: http://www.quirksmode.org/dom/inputfile.html

  • 本文向大家介绍ionic使用angularjs表单验证(模板验证),包括了ionic使用angularjs表单验证(模板验证)的使用技巧和注意事项,需要的朋友参考一下 1什么是模板验证 顾名思义模板验证就是通过一些angularjs的属性来在html标签中验证,为了往模板驱动表单中添加验证机制,你要添加一些验证属性,就像原生的 HTML 表单验证器。 Angular 会用指令来匹配这些具有验证功能

  • 本文向大家介绍HTML5和JavaScript: input type=file capture=camera,包括了HTML5和JavaScript: input type=file capture=camera的使用技巧和注意事项,需要的朋友参考一下 当设备正在拍摄非常大的照片并且我们想要进行这种设置以从手机中拍摄较小的照片时,我们可以使用两种W3C方式拍摄照片。 这可以通过HTML或Java

  • 问题内容: 如何在AngularJs中使用基本身份验证?我已经在Google上搜索了,但是资源对我来说不起作用。我 非常 新AngularJS 问题答案: 假设您的html定义如下: 您可以使用以下基本身份验证将后端连接到rest api: 请注意,此代码的大部分是方法。如果不需要支持IE9及更低版本,则可以将其替换为本地JS实现- atob()和btoa():https : //develope

  • 本文向大家介绍如何使用jQuery验证表单?,包括了如何使用jQuery验证表单?的使用技巧和注意事项,需要的朋友参考一下 首先,您必须制作一个类似html的表单。 现在使用jQuery验证插件以更简单的方式验证表单的数据。 首先,在文件中添加jQuery库。 然后使用简单语法定义规则。 定义错误消息。 现在终于提交表格了。