How to set the cursor focus on input field?
13,091
Solution 1
Option 1
HTML autofocus
Option 2
Try playing with ng-focus from angular.
Update
My bad, ng-focus
, from the doc:
Specify custom behavior on focus event.
So ng-focus is not what you need to use. keep on autofocus
.
Final solution with ng-if
https://plnkr.co/edit/sb29aGHGtdFQ7fiLdbtN?p=preview
Create a directive that will apply the focus for you.
myApp.directive('yourAutofocus', ['$timeout', function($timeout) {
return {
restrict: 'A',
link : function($scope, $element) {
$element[0].focus();
}
}
}]);
Solution 2
Try like this
ng-if="showMe" ng-focus="true && showMe" or ng-focus="focudMe=true; showMe=true"
Related videos on Youtube
Author by
Onestone
Updated on September 16, 2022Comments
-
Onestone over 1 year
I would like to set the cursor focus on an input field as soon as the form (directive) is shown. I tried adding the following code to my link function:
link: function (scope, element, attrs) { element('input[name=headline]').focus(); }
But it does not work. I also tried the following variants:
element.find('input[name=headline]').focus(); element.querySelector('input[name=headline]').focus();
I did not find any useful information on the Web.
md-autofocus
seems to have nothing to do with what I am trying to achieve. -
Onestone over 7 yearsThanks! In the meantime, I found the HTML autofocus attribute also. It works for the first time, but when the directive is recreated (ng-if), it no longer works. As for ng-focus, it seems to call a function when the input field gets focus... right?
-
Alteyss over 7 yearsUpdated my answer. Hope it helps.