Can't focus input in AngularJS
I am trying to focus an input field with AngularJS. I created a custom directive for this, but for some reason it doesn't work on a specific input field.
This is my "focus" directive:
angular.module('app.ui.input').directive('ooFocus', function()
{
return {
scope : {
trigger : '=ooFocus'
},
restrict : 'A',
link : function(scope, element, attrs)
{
scope.$watch('trigger', function(value)
{
if(value)
{
console.log('this will be printed');
element[0].focus();
element[0].select();
}
});
}
}
});
And this is how it looks when applied to an input field:
<input placeholder="Company name" type="text" ng-model="company.name" ng-blur="hide()" oo-focus="show" required>
The form containing the input field is hidden and displayed when show
set to true. show
is passed to the directive oo-focus
and I can see that the directive prints this will be printed
to the console if the parameter is show
set to true, but for some reason the input is not focused.
source to share
You cannot focus what is hidden, it is that simple. Therefore, you must be sure that yours is input
displayed before trying to focus it.
The problem is that usually you don't work with css
directly, which immediately shows the element. Usually you use a directive like ng-show
or ng-if
, and you can't even be sure that they evaluate to before ooFocus
.
Using $timeout
focus for delay is a good solution for this situation.
source to share
I have one job for this. Try using $ timeout inside a directive like
.directive('ooFocus',function($timeout) {
return {
scope : {
trigger : '=ooFocus'
},
restrict : 'A',
link : function(scope, element) {
scope.$watch('trigger', function(value) {
if (value) {
$timeout(function() {
element[0].focus();
});
}
});
}
};
});
source to share