2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to set focus on input field?

What is the "Angular way" to set focus on input field in AngularJS?

More specific requirements:

    When a Modal is opened, set focus on a predefined <input> inside this Modal.
    Everytime <input> becomes visible (e.g. by clicking some button), set focus on it.

I tried to achieve the first requirement with autofocus, but this works only when the Modal is opened for the first time, and only in certain browsers (e.g. in Firefox it doesn"t work).

Any help will be appreciated.

userimage
Usage

<input type="text" focus-on="focusMe"/>

app.controller('MyCtrl', function($scope, focus) {
    focus('focusMe');
});

Source

app.directive('focusOn', function() {
   return function(scope, elem, attr) {
      scope.$on('focusOn', function(e, name) {
        if(name === attr.focusOn) {
          elem[0].focus();
        }
      });
   };
});

app.factory('focus', function ($rootScope, $timeout) {
  return function(name) {
    $timeout(function (){
      $rootScope.$broadcast('focusOn', name);
    });
  }
});
Answer is