在Controller中使用$ setValidity

Chu*_*urk 75 javascript angularjs angularjs-controller angularjs-forms

我正在尝试对文件更改进行一些验证.这是我的代码:

查看/模板

<input type="file" name="file" id="file"  
       onchange="angular.element(this).scope().setFile(this)" 
       required />

<span class="error" ng-show="myForm.file.$error.required">Error</span>
<span class="error" ng-show="myForm.file.$error.size">Selected file is too large</span>
<span class="error" ng-show="myForm.file.$error.filetype">Unsupported File type</span>
Run Code Online (Sandbox Code Playgroud)

调节器

angular.module("myapp").controller("myctrl", function($scope) {
  $scope.setFile = function(element) {
    $scope.$apply(function($scope) {
      var fileObject = element.files[0];
      $scope.file.fileType = 
         fileObject.type.toUpperCase().substring(fileObject.type.indexOf("/") + 1);

      // Validation
      if (!$scope.isValidFileType($scope.file.fileType)) {
        myForm.file.$setValidity("myForm.file.$error.filetype", false);
      }

      if (fileObject.size > 1000*1000*10) {
        myForm.file.$setValidity("myForm.file.$error.size", false);
      }
    });
  };

  $scope.isValidFileType = function(fileExtension) {
    var supportedExtensions = ["doc", "docx", "ppt", "pptx", "jpg", "gif", "png"]; // etc.
    return (jQuery.inArray(fileExtension, supportedExtensions) > -1);
  }
});
Run Code Online (Sandbox Code Playgroud)

但是现在呼叫$setValidity不起作用.
有什么想法吗?

Ben*_*esh 126

这一行:

myForm.file.$setValidity("myForm.file.$error.size", false);
Run Code Online (Sandbox Code Playgroud)

应该

$scope.myForm.file.$setValidity("size", false);
Run Code Online (Sandbox Code Playgroud)


Mar*_*cok 17

需要在ngModelController上调用$ setValidity.在控制器内部,我认为这意味着$scope.myForm.file.$setValidity().

如果您还没有,请参见表单页面上的"自定义验证"部分.

另外,对于$ setValidity的第一个参数,只使用'filetype'和'size'.