I am trying to focus first empty input inside a html form using angularjs directive. Here is the directive code which I have written so far (and applied on form element):
.directive('focusFirstEmptyInput', ['$timeout', function ($timeout) {
return {
restrict: "A",
link: function (scope, element, attrs) {
var focustElement = function () {
var keepGoing = true;
angular.forEach(element[0], function (field) {
if (!keepGoing) {
return;
}
if (field.tagName.toLowerCase() !== 'input')
return;
debugger;
var fieldValue = field.value;
if (!fieldValue) {
field.focus();
keepGoing = false;
}
});
};
$timeout(focustElement, 0);
}
};
}]);
I am iterating over all form elements and trying to focus first empty field. However, when I am calling focus(), element doesn't get focused. What can be the reason?
UPDATE:
Weird, but if I remove the debugger statement (or don't open inspector mode at all) and don't pause the javascript code, it will focus first empty element.... (I am using Google Chrome)
Plunker: http://plnkr.co/edit/YT0DoTjUVrrnVwmyrX0v?p=preview