Skip to content Skip to sidebar Skip to footer

Setting Focus When Showing A Form Input In Angularjs

I've created a simple task list in AngularJS. http://jsfiddle.net/simonbingham/RX63v/ HTML <

Solution 1:

According to that answer, the simplest way is to focus the element and set:

el.selectionStart = el.selectionEnd = el.value.length;

You can create a custom directive that does that when a certain condition becomes true (and pass it the same condition that is passed to ngShow. This directive, will effectively set the cursor at the end of the text-field, when it get's displayed.

E.g.:

.directive('focusInputOn', function ($timeout) {
  return {
    restrict: 'A',
    link: functionfocusInputOnPostLink(scope, elem, attrs) {
      attrs.$observe('focusInputOn', function (newValue) {
        if (newValue) {
          // Since the element will become visible (and focusable) after// the next render event, we need to wrap the code in `$timeout`$timeout(function () {
            var el = elem[0];
            el.focus();
            el.selectionStart = el.selectionEnd = el.value.length;
          });
        }
      });
    }
  };
});

<input type="text" ... ng-show="showInput" focus-input-on="{{showInput}}" />

See, also, this short demo.


Make sure you test this feature on all browsers you plan to support, because some older browsers might not support certain things. I tested it on latest Chrome (v35), latest Firefox (v30) and IE v10/11 and it works fine.

Post a Comment for "Setting Focus When Showing A Form Input In Angularjs"