必要属性不使用文件输入工作在角的js(Required attribute Not working

2019-09-01 02:28发布

我在我的form.I文件上传控件现在用角JS。 当我把所需要的属性,以验证该文件被选中它无法正常工作。

<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>

能否请你说明为什么需要的是不工作?

Answer 1:

这是ngModelController ,做基于属性的像角的验证require 。 然而,目前不存在用于支持input type="file"与NG-模型的服务。 为了得到它的工作,你可以创建这样一个指令:

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

示例标记:

  <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>

看看我的工作plnkr例子 。



Answer 2:

扩展@joakimbl代码我会建议直接像这样

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

在HTML中你可以使用这样

<input type="file" name="myFile" ng-model="myFile" valid-file />
<label ng-show="myForm.myFile.$error.validFile">File is required</label>


文章来源: Required attribute Not working with File input in Angular Js