将焦点设置在 AngularJs 表单中的第一个无效输入上 [英] Set focus on first invalid input in AngularJs form
问题描述
我已经阅读了几篇与 AngularJs 中的焦点设置相关的文章和 StackOverflow 问题.
I've read several articles and StackOverflow questions relating to the setting of focus in AngularJs.
不幸的是,我读过的所有示例都假设有一些属性可以添加到元素中以获得焦点,例如focusMe 指令.
Unfortunately all the examples that I have read assume that there is some attribute that I can add to the element to gain focus, e.g. a focusMe directive.
但是如果我事先不知道将焦点设置到哪个输入怎么办?特别是如何将焦点设置为具有 $invalid 设置的表单中的第一个输入元素 - 即未通过验证的元素.可能有几个输入验证失败,因此我不能使用仅尝试基于此调用 .focus() 的指令.(我这样做是出于可访问性/WCAG 的原因,这是一种很好的做法,即在点击提交时这样做以尽量减少按键以找到第一个验证失败的字段.
However what if I don't know in advance which input to set focus to? In particular how do I set focus to the first input element in a form that has $invalid set - i.e. an element that fails validation. There could be several inputs that fail validation, so I cannot use a directive that just tries to call .focus() based on this. (I am doing this for Accessibility/WCAG reasons, its good practice to do so on submit being clicked to minimize keypresses to find the first field that has failed validation).
$error 对象将提供所有未通过验证的控件,但它们按失败类型分组,而不是按在表单上的任何出现顺序进行分组.
The $error object will give all controls that fail validation, but they are grouped by the type of failure not in any order of appearance on the form.
我相信我可以想出一些笨拙的方法来做到这一点.表单上的指令,在需要设置焦点时接收一些广播 - 然后该指令可以搜索第一个 $invalid 元素.然而,这似乎非常复杂,我想知道这是否是一种更好的、更有角度"的方式.
I'm sure I can come up with some kludged way of doing this. A directive on the form, which receives some broadcast when focus needs to be set - that directive can then search for the first $invalid element. However this seems very complex and I'd like to know whether these is a better more 'angular' way of doing this.
推荐答案
你也可以使用 angular.element
You can also use angular.element
angular.element('input.ng-invalid').first().focus();
查看
<form name="myForm" novalidate="novalidate" data-ng-submit="myAction(myForm.$valid)" autocomplete="off"></form>
控制器
$scope.myAction= function(isValid) {
if (isValid) {
//You can place your ajax call/http request here
} else {
angular.element('input.ng-invalid').first().focus();
}
};
使用 ngMessages 进行验证
used ngMessages for validation
没有jquery的方式
angular.element($document[0].querySelector('input.ng-invalid')).focus();
使用此方法时,需要将$document
作为参数传入你的角度控制器
When using this method, need to pass $document
as parameter in your angular controller
angular.module('myModule')
.controller('myController', ['$document', '$scope', function($document, $scope){
// Code Here
}]);
这篇关于将焦点设置在 AngularJs 表单中的第一个无效输入上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!