Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to put a default focus on an element in AngularJS?

Tags:

I have a template that is loaded in a modal dialog, there is a single input text on it which I would like to have a focus on. What is the easiest and the Angular way of doing that?

Update:

This is in part answered in How to set focus on input field?

like image 493
user3111525 Avatar asked Sep 20 '13 15:09

user3111525


People also ask

What is focus in AngularJS?

AngularJS ng-focus DirectiveThe ng-focus directive tells AngularJS what to do when an HTML element gets focus. The ng-focus directive from AngularJS will not override the element's original onfocus event, both will be executed.

How do you focus on a form element?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.


2 Answers

Depending on the browser(s) you need to support you could use input autofocus attribute.

See plunker here.

Or if this is not an option and has mentioned by Mark you can refer to the following stackoverflow response.

like image 86
Nicolas ABRIC Avatar answered Oct 21 '22 07:10

Nicolas ABRIC


How about this?

HTML

  <div ng-controller="ctrl as vm" ng-init="vm.focus();"> <form name="Form">   <input type="text" id="input1">   <input type="text" id="input2"> </form> 

JS

   angular.module('app', []).controller('ctrl', function() {     var vm = this;      vm.focus = function() {       document.getElementById('input2').focus();     };    }); 

https://plnkr.co/edit/noLUjVjycpnezpvEIgw7?p=preview

like image 44
user2828511 Avatar answered Oct 21 '22 08:10

user2828511