-1

Using AngularJS how can I focus a text input from a controller?

I have tried using the following:

$scope.myinput.focus();

This throws an error: "undefined' is not an object (evaluating '$scope.myinput.focus')"

The basic situation is to trigger a focus of the input from clicking on another element. Ive created a fiddle to show the problem.

Note: I am not interested in jquery solutions.

Thanks for your help.

Paul Haggo
  • 1,338
  • 1
  • 11
  • 20
  • 1
    Check out directive in answer at http://stackoverflow.com/questions/14076783/angularjs-focusing-a-input-element-when-a-checkbox-is-clicked – Mike Pugh Dec 19 '13 at 01:54

1 Answers1

1

Give the text box an ID and focus it using basic javascript:

document.getElementById('theboxid').focus();

A principle of Angular is to avoid coupling with the DOM though, so that code should not be in your controller for testability reasons. It's bad practice, but you can do it.

Fiddle here: http://jsfiddle.net/mh33X/14/

Marc
  • 11,403
  • 2
  • 35
  • 45
  • It seems that angular is unable to set the focus of elements. Your answer works and does not use Jquery - further explanation would be helpful though. – Paul Haggo Dec 19 '13 at 09:35