From bdfb28916e10397eb652fe540ef30081e9e250a8 Mon Sep 17 00:00:00 2001 From: Wesley Cho Date: Sun, 23 Aug 2015 06:25:47 -0700 Subject: [PATCH] feat(buttons): allow toggling via spacebar when focused - Allow the spacebar to toggle the button state when focused Closes #4252 Closes #4259 --- src/buttons/buttons.js | 16 +++++++++++++-- src/buttons/test/buttons.spec.js | 35 ++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/buttons/buttons.js b/src/buttons/buttons.js index 7253b6a62a..ecec408dd5 100644 --- a/src/buttons/buttons.js +++ b/src/buttons/buttons.js @@ -42,7 +42,7 @@ angular.module('ui.bootstrap.buttons', []) }; }) -.directive('btnCheckbox', function() { +.directive('btnCheckbox', ['$document', function($document) { return { require: ['btnCheckbox', 'ngModel'], controller: 'ButtonsController', @@ -79,6 +79,18 @@ angular.module('ui.bootstrap.buttons', []) ngModelCtrl.$render(); }); }); + + //accessibility + element.on('keypress', function(e) { + if (attrs.disabled || e.which !== 32 || $document[0].activeElement !== element[0]) { + return; + } + + scope.$apply(function() { + ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue()); + ngModelCtrl.$render(); + }); + }); } }; -}); +}]); diff --git a/src/buttons/test/buttons.spec.js b/src/buttons/test/buttons.spec.js index d8d152b2d5..9ac5d29c0b 100644 --- a/src/buttons/test/buttons.spec.js +++ b/src/buttons/test/buttons.spec.js @@ -74,6 +74,27 @@ describe('buttons', function() { expect(btn).not.toHaveClass('active'); }); + it('should toggle custom model values on spacebar if focused', function() { + $scope.model = 0; + var btn = compileButton('', $scope); + $('body').append(btn); + var e = $.Event('keypress'); + e.which = 32; + + btn[0].focus(); + btn.trigger(e); + $scope.$digest(); + expect($scope.model).toEqual(1); + expect(btn).toHaveClass('active'); + + btn.trigger(e); + $scope.$digest(); + expect($scope.model).toEqual(0); + expect(btn).not.toHaveClass('active'); + + btn.remove(); + }); + it('should monitor true / false value changes - issue 666', function() { $scope.model = 1; @@ -95,6 +116,7 @@ describe('buttons', function() { $scope.model = 1; $scope.falseVal = 0; var btn = compileButton('', $scope); + $('body').append(btn); expect(btn).not.toHaveClass('active'); expect($scope.model).toEqual(1); @@ -106,6 +128,19 @@ describe('buttons', function() { $scope.$digest(); expect(btn).not.toHaveClass('active'); + + btn[0].focus(); + var e = $.Event('keypress'); + e.which = 32; + btn.trigger(e); + + expect(btn).not.toHaveClass('active'); + + $scope.$digest(); + + expect(btn).not.toHaveClass('active'); + + btn.remove(); }); describe('setting buttonConfig', function() {