23

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?

Community
  • 1
  • 1
user3111525
  • 5,013
  • 9
  • 39
  • 64
  • 1
    You can use `ng-focus` depending on the version of angular you are using. As the poster in the following question states you can create your own ng-focus directive. http://stackoverflow.com/questions/18549142/ng-focus-and-ng-blur-events-not-triggering-in-angularjs – Jonathan Palumbo Sep 20 '13 at 16:47
  • 1
    See also http://stackoverflow.com/a/14837021/215945 which deals with setting focus inside a modal dialog. – Mark Rajcok Sep 20 '13 at 18:01

3 Answers3

21

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.

Community
  • 1
  • 1
Nicolas ABRIC
  • 4,925
  • 28
  • 18
4

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

  • Does not seem to work, either in my code or the plunker, either in the embedded preview or in a separate window: the two inputs show up, but the second is not focused. Breakpoint indicates the focus function is never called. – JohnT Feb 13 '19 at 23:00
0

The simplest solution I've found is to call focus inside a $timeout wrap.

Controller:

$timeout(function () { $('#input1').focus(); });
Fabiano Cores
  • 189
  • 1
  • 2