1

I have an input field and a $watch over its scope variable that triggers some server request. I disable the field during the request, but when it gets re-enabled again, cursor is missing from the line. I would like it to be present again.

I tried to restore focus by means of e.g. directive How to set focus on input field? but it does not work for some reason in connection with enabling/disabling field (I set both "focusing" and "enabling" variables in the same time.)

Community
  • 1
  • 1
onkami
  • 8,791
  • 17
  • 90
  • 176

2 Answers2

4

create a directive

app.directive('focusMe', function($timeout) {
  return {
    scope: {
      trigger: '=focusMe'
    },
    priority: -1,
    link: function(scope, element) {
      scope.$watch('trigger', function(value) {
        if (value === true) {
          $timeout(function() {
            element[0].focus();
            scope.trigger = false;
          }, 300);
        }
      });
    }
  };
});

add directive to the input field

<input type="text" focus-me="focusInput" data-ng-model="myModel" required .. />

within controller

$scope.focusInput=true;

when $scope.focusInput is true the input field will be focused

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
1

Easy way

<input type="text" ng-disabled="true" required ... />

After the event when you want enable and focus the input you should do this in your .ts file

$scope.enableInput = function () {
  document.getElementById("password").disabled = false;
  document.getElementById('password').focus();
};

That is haw you restore focus to text input field after setting it disabled and enabled again using AngularJS