user3111525
user3111525

Reputation: 5203

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

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?

Upvotes: 23

Views: 42754

Answers (3)

Fabiano Cores
Fabiano Cores

Reputation: 199

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

Controller:

$timeout(function () { $('#input1').focus(); });

Upvotes: 0

user2828511
user2828511

Reputation: 41

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

Upvotes: 4

Nicolas ABRIC
Nicolas ABRIC

Reputation: 4935

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.

Upvotes: 21

Related Questions