Set focus on first invalid input in AngularJs form

前端 未结 13 1453
-上瘾入骨i
-上瘾入骨i 2020-12-04 18:55

I\'ve read several articles and StackOverflow questions relating to the setting of focus in AngularJs.

Unfortunately all the examples that I have read assume that th

13条回答
  •  生来不讨喜
    2020-12-04 19:39

        .directive('accessibleForm', function () {
            return {
                restrict: 'A',
                link: function (scope, elem) {
                    // set up event handler on the form element
                    elem.on('submit', function () {
                        // find the first invalid element
                        var firstInvalid = elem[0].querySelector('.ng-invalid');
                        if (firstInvalid && firstInvalid.tagName.toLowerCase() === 'ng-form') {
                            firstInvalid = firstInvalid.querySelector('.ng-invalid');
                        }
                        // if we find one, set focus
                        if (firstInvalid) {
                            firstInvalid.focus();
                        }
                    });
                }
            };
        })

提交回复
热议问题