Skip to content
This repository has been archived by the owner on May 29, 2019. It is now read-only.

Commit

Permalink
fix(modal): Autofocus corrects the second time that the modal is open
Browse files Browse the repository at this point in the history
element with autofocus attribute when the modal is reopened

Fixes #2802
  • Loading branch information
ddomingues authored and wesleycho committed Mar 23, 2015
1 parent 2c2dba6 commit e5f5f75
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
7 changes: 7 additions & 0 deletions misc/test-lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ beforeEach(function() {
var element = angular.element(this.actual);
return element.hasClass('ng-hide') ||
element.css('display') == 'none';
},
toHaveFocus: function () {
this.message = function () {
return 'Expected \'' + angular.mock.dump(this.actual) + '\' to have focus';
};

return document.activeElement === this.actual[0];
}
});
});
5 changes: 4 additions & 1 deletion src/modal/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition'])
// trigger CSS transitions
scope.animate = true;

var inputsWithAutofocus = element[0].querySelectorAll('[autofocus]');
/**
* Auto-focusing of a freshly-opened modal element causes any child elements
* with the autofocus attribute to lose focus. This is an issue on touch
Expand All @@ -127,7 +128,9 @@ angular.module('ui.bootstrap.modal', ['ui.bootstrap.transition'])
* the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
* the modal element if the modal does not contain an autofocus element.
*/
if (!element[0].querySelectorAll('[autofocus]').length) {
if (inputsWithAutofocus.length) {
inputsWithAutofocus[0].focus();
} else {
element[0].focus();
}

Expand Down
16 changes: 16 additions & 0 deletions src/modal/test/modal.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,22 @@ describe('$modal', function () {
expect(modal.opened).toBeRejectedWith(false);
});

it('should focus on the element that has autofocus attribute when the modal is open/reopen', function () {
function openAndCloseModalWithAutofocusElement() {
var modal = open({template: '<div><input type="text" id="auto-focus-element" autofocus></div>'});

waitForBackdropAnimation();

expect(angular.element('#auto-focus-element')).toHaveFocus();

close(modal, 'closed ok');

expect(modal.result).toBeResolvedWith('closed ok');
}

openAndCloseModalWithAutofocusElement();
openAndCloseModalWithAutofocusElement();
});
});

describe('default options can be changed in a provider', function () {
Expand Down

0 comments on commit e5f5f75

Please sign in to comment.