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.
You can also use the jqlite functionality built into angular.
angular.element('.selector').trigger('focus');
This works well and an angular way to focus input control
This is although not a pure angular way of doing the task yet the syntax follows angular style. Jquery plays role indirectly and directly access DOM using Angular (jQLite => JQuery Light).
If required, this code can easily be put inside a simple angular directive where element is directly accessible.
A simple one that works well with modals:
Example
The following directive did the trick for me. Use the same autofocus html attribute for input.
Probably, the simplest solution on the ES6 age.
Adding following one liner directive makes HTML 'autofocus' attribute effective on Angular.js.
Now, you can just use HTML5 autofocus syntax like:
Just throwing in some coffee.