必需属性不适用于 Angular Js 中的文件输入 [英] Required attribute Not working with File input in Angular Js

查看:19
本文介绍了必需属性不适用于 Angular Js 中的文件输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单中有一个文件上传控件.我使用的是 Angular JS.当我输入 required 属性来验证文件被选中时,它不起作用.

<button type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>

你能建议为什么所需的不起作用吗?

解决方案

ngModelController 根据 require 等属性在 Angular 中进行验证.但是,目前 ng-model 服务不支持 input type="file".为了让它工作,你可以创建一个这样的指令:

app.directive('validFile',function(){返回 {要求:'ngModel',链接:功能(范围,EL,属性,ngModel){//文件被选中时触发change事件el.bind('改变',function(){范围.$应用(函数(){ngModel.$setViewValue(el.val());ngModel.$render();});});}}});

示例标记:

 

<input id="userUpload" ng-model="filename" valid-file name="userUpload" required type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/><button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;确定</button><p>输入有效:{{myForm.userUpload.$valid}}
所选文件:{{文件名}}</p>

查看我的工作 plnkr 示例.

I have a file upload control in my form.I am using Angular JS . When I put the required attribute to validate that the file is selected it is not working.

<input id="userUpload" name="userUpload" required type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

<button type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>

Can you please suggest why the required is not working ?

解决方案

It's the ngModelController that does the validation in Angular based on attributes like require. However, currently there is no support for input type="file" with the ng-model service. To get it working you could create a directive like this:

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

Example markup:

  <div ng-form="myForm">
    <input id="userUpload" ng-model="filename" valid-file name="userUpload" required type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
    <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>
    <p>
      Input is valid: {{myForm.userUpload.$valid}}
      <br>Selected file: {{filename}}
    </p>
  </div>

Check out my working plnkr example.

这篇关于必需属性不适用于 Angular Js 中的文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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