Reputation: 18107
Using ui-bootstrap with this attribute attached to the ok/save button on the dialog. The first time my dialog is created, it focuses on the button just as expected. Every subsequent time it has no effect.
.directive('autoFocus', function($timeout) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$timeout(function(){
_element[0].focus();
}, 0);
}
};
});
The modal template looks like this (This comes from Michael Conroy's angular-dialog-service):
<div class="modal" ng-enter="" id="errorModal" role="dialog" aria-Labelledby="errorModalLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header dialog-header-error">
<button type="button" class="close" ng-click="close()">×
</button>
<h4 class="modal-title text-danger"><span class="glyphicon glyphicon-warning-sign"></span> Error</h4>
</div>
<div class="modal-body text-danger" ng-bind-html="msg"></div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" autoFocus ng-click="close()">Close</button>
</div>
</div>
</div>
</div>
The first time the focus moves to the close button no problem. After that the focus stays where it was.
I'm trying to deal with an enter key keypress that is launching this error dialog repeatedly, and I really need the focus to move away from the from underneath the dialog.
Upvotes: 1
Views: 2362
Reputation: 18107
Turns out that autofocus is a really bad choice for a directive. I renamed it takefocus and now it works every time without any change. Why does autofocus not work? Beats me. There are override directives for and other tags that are in angular and work, but overriding autofocus with a directive does not.
Upvotes: 2
Reputation: 8465
It happens because the directive autoFocus is compiled once when the element is added to stage and the link function isn't called again, if you have a variable on parent scope responsible for displaying modal like $scope.opened
you can use $watcher on said variable, i.e. if ith change from false to true set focus
.directive('autoFocus', function($timeout, $watch) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$watch('_scope.opened', function (newValue) {
if(newValue){
$timeout(function(){
_element[0].focus();
}, 0);
}
}
}
};
});
Upvotes: 1