Set focus on first invalid input in AngularJs form

前端 未结 13 1423
-上瘾入骨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:32

    I was inspired by chaojidan above to suggest this variation for those who are using nested angular 1.5.9 ng-forms:

    class FormFocusOnErr implements ng.IDirective
    {
        static directiveId: string = 'formFocusOnErr';
    
        restrict: string = "A";
    
        link = (scope: ng.IScope, elem, attrs) =>
        {
            // set up event handler on the form element
            elem.on('submit', function () {
    
                // find the first invalid element
                var firstInvalid = angular.element(
                    elem[0].querySelector('.ng-invalid'))[0];
    
                // if we find one, set focus
                if (firstInvalid) {
                    firstInvalid.focus();
                    // ng-invalid appears on ng-forms as well as 
                    // the inputs that are responsible for the errors.
                    // In such cases, the focus will probably fail 
                    // because we usually put the ng-focus attribute on divs 
                    // and divs don't support the focus method
                    if (firstInvalid.tagName.toLowerCase() === 'ng-form' 
                        || firstInvalid.hasAttribute('ng-form') 
                        || firstInvalid.hasAttribute('data-ng-form')) {
                        // Let's try to put a finer point on it by selecting 
                        // the first visible input, select or textarea 
                        // that has the ng-invalid CSS class
                        var firstVisibleInvalidFormInput = angular.element(firstInvalid.querySelector("input.ng-invalid,select.ng-invalid,textarea.ng-invalid")).filter(":visible")[0];
                        if (firstVisibleInvalidFormInput) {
                            firstVisibleInvalidFormInput.focus();
                        }
                    }
                }
            });            
        }
    }
    
    // Register in angular app
    app.directive(FormFocusOnErr.directiveId, () => new FormFocusOnErr());
    

提交回复
热议问题