Javascript 在控制器中使用 $setValidity
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14363656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using $setValidity inside a Controller
提问by Churk
I am trying to do some validation on file change. Here is my code:
我正在尝试对文件更改进行一些验证。这是我的代码:
View/Template
视图/模板
<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>
Controller
控制器
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);
}
});
But right now the call to $setValidityis not working.
Any thoughts?
但是现在对 的调用$setValidity不起作用。
有什么想法吗?
回答by Ben Lesh
This line:
这一行:
myForm.file.$setValidity("myForm.file.$error.size", false);
Should be
应该
$scope.myForm.file.$setValidity("size", false);
回答by Mark Rajcok
$setValidity needs to be called on the ngModelController. Inside the controller, I think that means $scope.myForm.file.$setValidity().
$setValidity 需要在 ngModelController 上调用。在控制器内部,我认为这意味着$scope.myForm.file.$setValidity().
See also section "Custom Validation" on the Forms page, if you haven't already.
另请参阅“表单”页面上的“自定义验证”部分(如果您还没有)。
Also, for the first argument to $setValidity, use just 'filetype' and 'size'.
此外,对于 $setValidity 的第一个参数,只需使用“filetype”和“size”。
回答by Alvin Chettiar
A better and optimised solution to display multiple validation messages for a single element would be like this.
为单个元素显示多个验证消息的更好和优化的解决方案是这样的。
<div ng-messages="myForm.file.$error" ng-show="myForm.file.$touched">
<span class="error" ng-message="required"> <your message> </span>
<span class="error" ng-message="size"> <your message> </span>
<span class="error" ng-message="filetype"> <your message> </span>
</div>
Controller Code should be the one suggested by @ Ben Lesh
控制器代码应该是@Ben Lesh 建议的代码

