11

Is there any way to set focus in input controls using AngularJS/Angular-UI ?

I saw that Angular-UI has some Jq-UI=focus directive but I'm unable to get it to work.

I have a few dialogs that I display using Angular-UI $dialog service and would really like the first input on each dialog to get focus once it's shown

Roger Johansson
  • 22,764
  • 18
  • 97
  • 193

4 Answers4

19

I used the standard autofocus attribute in my template, and declared a simple directive to make it work for elements that are created after page load (like dialogs in your case).

app.directive('autofocus', function () {
  return {
    restrict: 'A',
    link: function (scope, element) {
      element[0].focus();
    }
  };
});
Yann Dìnendal
  • 1,422
  • 2
  • 17
  • 27
10

Turns out that all you need is this if you use it together with the Angular-ui $dialog service:

app.directive('focusMe', function ($timeout) {    
    return {    
        link: function (scope, element, attrs, model) {                
            $timeout(function () {
                element[0].focus();
            });
        }
    };
});

html:

  <input type="text" focus-me >

as stated, this is for Angular-UI $dialog service only.

See it live here: http://strengthtracker.apphb.com (click login or register to bring up the dialogs)

Roger Johansson
  • 22,764
  • 18
  • 97
  • 193
0

You are right, I've shown demos on how you can call jQuery's native jQuery.fn.focus() method on a DOM element, as that's all ui-jq really does. The trick is getting it to fire multiple times, and at the right time.

ui-jq already executes the method for you inside a $timeout, however by default it only fires once, when the DOM element is created. In order to make ui-jq fire multiple times, simply add ui-refresh="someExpression" and use an expression that you know will change every single time the modal opens. It's alright if it refires when the modal is closed too, .focus() will do nothing if the DOM element is not visible.

So, for the ui-bootstrap modal, simply put the same expression you're using inside the modal="someExpression" and you should be set.

ProLoser
  • 4,616
  • 2
  • 16
  • 23
-5

The last version of AngularJS offers ng-focus : http://docs.angularjs.org/api/ng/directive/ngFocus

EpokK
  • 38,062
  • 9
  • 61
  • 69