diff --git a/misc/test-lib/helpers.js b/misc/test-lib/helpers.js index 4d9d606397..b3d4b0fb50 100644 --- a/misc/test-lib/helpers.js +++ b/misc/test-lib/helpers.js @@ -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]; } }); }); diff --git a/src/modal/modal.js b/src/modal/modal.js index 5b950e03c4..c9dc529599 100644 --- a/src/modal/modal.js +++ b/src/modal/modal.js @@ -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 @@ -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(); } diff --git a/src/modal/test/modal.spec.js b/src/modal/test/modal.spec.js index a9ba449538..ff8107328c 100644 --- a/src/modal/test/modal.spec.js +++ b/src/modal/test/modal.spec.js @@ -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: '
'}); + + 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 () {