Set focus on first invalid input in AngularJs form

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

    I have been playing with this idea for a while and I came up with my own solution, it may help people who are adverse to crawling the DOM, like me.

    As far as I can tell form elements register themselves in a consistent order (i.e. top to bottom) and their names and validation states are available on the scope through what ever the form name is (e.g. $scope.myForm).

    This lead me to think that there was a way to find the first invalid form input without crawling the DOM and instead crawling the internal structures of angular js. Below is my solution but it assumes that you have some other way of focusing form elements, I am broadcasting to a custom directive, if the broadcast matches the name of the element it will focus itself (which is useful in itself as you you get to control which element takes focus on the first load).

    The function to find the first invalid (ideally shared to the controllers through a service)

    function findFirstInvalid(form){
        for(var key in form){
            if(key.indexOf("$") !== 0){
                if(form[key].$invalid){
                    return key;
                }
            }
        }
    }
    

    And the custom focus directive

    directives.directive('focus', function($timeout){
        return {
            require: 'ngModel',
            restrict: 'A',
            link: function(scope, elem, attrs, ctrl){
                scope.$on('inputFocus', function(e, name){
                    if(attrs.name === name){
                        elem.focus();
                    }
                });
            }
        }
    });
    

提交回复
热议问题