在控制器中使用 $setValidity [英] Using $setValidity inside a Controller

查看:29
本文介绍了在控制器中使用 $setValidity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to do some validation on file change. Here is my code:

视图/模板

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

控制器

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

但是现在对 $setValidity 的调用不起作用.
有什么想法吗?

But right now the call to $setValidity is not working.
Any thoughts?

推荐答案

这一行:

myForm.file.$setValidity("myForm.file.$error.size", false);

应该

$scope.myForm.file.$setValidity("size", false);

这篇关于在控制器中使用 $setValidity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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