1

I've got an angular directive that includes a form field as part of the template. If the focusOnShow attribute is set to true, the directive will attempt to focus on the field when tha directive is added to the page's DOM.

if (scope.focusOnShow) {
    var input = el.find('input')[0];
    $timeout(function () {                  
        el.find('input')[0].focus();
    }, 500); //well this is crap
}

I'm using this in a modal (angular directives for bootstrap), and the focus() is firing before the field is available because of the modal transition time. If I wait .5 seconds, it works without a problem, but that's lame and unreliable. Is there a way to know that the field is "focusable" before attempting to call focus() on it?

sonicblis
  • 2,926
  • 7
  • 30
  • 48
  • Can you hook the focus to a modal transition callback or maybe a close/open/transitionEnd event? Using transitions makes your code inherently asynchronous. The best way to deal with it is with event passing or callbacks. – zero298 Feb 16 '15 at 19:08
  • I thought about that since there is an 'opened' function on the promise returned by the modal.open(), but the modal is going to have a wizard like flow, so I need it to be a little more dynamic than that (and I'm not sure I would want DOM stuff connected to the modal 'opened' call). =\ – sonicblis Feb 16 '15 at 19:10
  • isn't it a duplicate: http://stackoverflow.com/questions/14833326/how-to-set-focus-on-input-field – Manube Feb 16 '15 at 19:15
  • Very similar. The key difference is that I'd like to have an implicit trigger on the focus call instead of an explicit one. With the solution in your link, I could still be calling focus() before the input is actually available to be focused on. – sonicblis Feb 16 '15 at 19:31

0 Answers0