Set focus on first invalid input in AngularJs form

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

    You can also use angular.element

    angular.element('input.ng-invalid').first().focus();
    

    View

    Controller

    $scope.myAction= function(isValid) {
        if (isValid) {
            //You can place your ajax call/http request here
        } else {
            angular.element('input.ng-invalid').first().focus();
        }
    };
    

    used ngMessages for validation

    The no jquery way

    angular.element($document[0].querySelector('input.ng-invalid')).focus();
    

    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
    }]);
    

提交回复
热议问题