Set focus on first invalid input in AngularJs form

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

    You can add an attribute in each form element which is a function (ideally a directive) that receives a field id. This field id would have to correlate somehow to your $error object. The function can check if the id is in your $error object, and if so return the attribute setting for an error.

    
    

    If you had an error, it would generate this.

    
    

    You can use this to set your style and you now know which fields have errors. Unfortunately you don't know which is the first field.

    One solution would be to use jQuery and the .first filter. If you go this route, check out http://docs.angularjs.org/api/angular.element

    Another solution would be to add into your form fields a field order parameter for the function: {{errorCheck('name', 1)}}. You could push the error field names to an array, then sort them by the field order parameter. This could give you more flexibility.

    Hope this helps.

提交回复
热议问题