24

我的表单中有一个文件上传控件。我正在使用 Angular 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>

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

4

2 回答 2

42

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

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

于 2013-04-25T07:33:22.943 回答
11

扩展@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>
于 2015-08-20T07:19:29.863 回答