Set focus on first invalid input in AngularJs form

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

    Ok, so the answer was simpler than I thought.

    All I needed was a directive to put on the form itself, with an event handler looking for the submit event. This can then traverse the DOM looking for the first element that has the .ng-invalid class on it.

    Example using jQLite:

    myApp.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 we find one, set focus
                    if (firstInvalid) {
                        firstInvalid.focus();
                    }
                });
            }
        };
    });
    

    The example here uses an Attribute directive, you could expand the example to have this be an element directive (restrict: 'E') and include a template that converts this to a . This is however a personal preference.

提交回复
热议问题