What is the 'Angular way' to set focus on input field in AngularJS?
More specific requirements:
- When a Modal is opened, set focus on a predefined
<input>
inside this Modal. - Everytime
<input>
becomes visible (e.g. by clicking some button), set focus on it.
I tried to achieve the first requirement with autofocus
, but this works only when the Modal is opened for the first time, and only in certain browsers (e.g. in Firefox it doesn't work).
Any help will be appreciated.
I have found some of the other answers to be overly complicated when all you really need is this
usage is
We use the timeout to let things in the dom render, even though it is zero, it at least waits for that - that way this works in modals and whatnot too
HTML has an attribute
autofocus
.http://www.w3schools.com/tags/att_input_autofocus.asp
It's easy.. try this
html
javascript
I found it useful to use a general expression. This way you can do stuff like automatically move focus when input text is valid
Or automatically focus when the user completes a fixed length field
And of course focus after load
The code for the directive:
I don't think $timeout is a good way to focus the element on creation. Here is a method using built-in angular functionality, dug out from the murky depths of the angular docs. Notice how the "link" attribute can be split into "pre" and "post", for pre-link and post-link functions.
Working Example: http://plnkr.co/edit/Fj59GB
Full AngularJS Directive Docs: https://docs.angularjs.org/api/ng/service/$compile
Just a newbie here, but I was abble to make it work in a ui.bootstrap.modal with this directive:
and in the $modal.open method I used the folowing to indicate the element where the focus should be putted:
on the template I have this: