I played with this idea for a while, and I came up with my own solution, it can help people who negatively scan the DOM like me.
As far as I can tell, form elements are registered in sequential order (i.e. from top to bottom), and their names and validation states are available in scope through what has ever been in the form name (for example, $ scope.myForm).
This made me think that there was a way to find the first invalid form input without going around the DOM and instead scan the internal structures of angular js instead. Below is my solution, but it assumes that you have another way of focusing the form elements, I transmit according to the user directive if the translation matches the name of the element that it will concentrate on its own (which is useful in itself, since you get the control focuses on first boot).
Search function for the first invalid (ideally shared with controllers through the 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(); } }); } } });
h.coates Feb 20 '14 at 4:52 2014-02-20 04:52
source share