Ludwig Magnusson Ludwig Magnusson - 1 month ago 7
AngularJS Question

Make input text selected upon appearance in angular

Using angular I have a set of input elements that become present in the dom after a certain user action, i.e I use

ng-if
to determine if it should be present or not. I would like the first of these input elements to gain focus and for the text in it to be selected to that the user easily can change all the content in that element.

Searching the web I have seen several posts that say I should use either the
focus
or
select
method or both but I haven't been able to get the desired result. Here is a directive I created:

app.directive('selectMe', function() {
return function(scope, element) {
element[0].focus();
element[0].select();
};
})


And here is a plunkr demo. Can anyone tell me why it is not working?

Answer

Because when your directive is initializing, their values isn't attached yet, therefore you should set small $timeout.

It works, you can try in plnkr

app.directive('selectMe', function($timeout) {
  return function(scope, element) {

    $timeout(function() {
      var ele = element[0];
     ele.focus();
     ele.select();
  }, 500)
Comments