Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies.
I love to learn new things in life that keep me motivated.
In AngularJS, you can set the focus to the input field programmatically or directly in your controller's logic through a directive. Here’s how you can do this.
Using a Directive (recommended method)
Define a Directive Create a custom directive to control set focus on each element.
Apply the Directive in HTML Apply the focusMe directive to your input field. The instruction requires a scope variable (focusInput) and will set focus on the element when the variable is true.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Set focus on input field
In AngularJS, you can set the focus to the input field programmatically or directly in your controller's logic through a directive. Here’s how you can do this.
Using a Directive (recommended method)
Define a Directive
Create a custom directive to control set focus on each element.
Apply the Directive in HTML
Apply the
focusMedirective to your input field. The instruction requires a scope variable (focusInput) and will set focus on the element when the variable is true.Set Focus in Controller
In your controller, set the
focusInputvariable totrueto trigger focus on the input field.Example-
In the example above
Directive (focusMe)
focusMedirective checks the focusInput value using$watch.$timeoutto delay the focus operation until after the current digestion cycle.element[0].focus()is used to focus on the first element of the element in the reference.HTML Usage
focus-me="focusInput"attribute of the<input>element binds the directive to the focusInput scope variable.Controller logic
focusInputvariable.focusInputtotruewhen a condition is satisfied (e.g., after a button is pressed, at startup, etc.).Also, Read: "this" vs $scope in AngularJS controllers