From 076f8983f3ca65a2292f079c55299791b18f4f15 Mon Sep 17 00:00:00 2001 From: Diego Domingues Date: Mon, 10 Nov 2014 11:21:02 -0200 Subject: [PATCH] fix(modal): Autofocus corrects the second time that the modal is open element with autofocus attribute when the modal is reopened Fixes #2802 --- misc/test-lib/helpers.js | 7 +++++++ src/modal/modal.js | 5 ++++- src/modal/test/modal.spec.js | 16 ++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) 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 () {