From 476d068c6f6e204d2c0797be08346076154a9029 Mon Sep 17 00:00:00 2001 From: Kenneth Cachia Date: Fri, 1 May 2015 10:27:01 -0700 Subject: [PATCH] fix(slider): increment the value properly when step is a decimal number switch from toFixed to Math.round update tests for predictable steps Closes #2015. Closes #2657. --- src/components/slider/slider.js | 4 +++- src/components/slider/slider.spec.js | 35 ++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/components/slider/slider.js b/src/components/slider/slider.js index f4a51d54f5e..f1ee3dd97e5 100644 --- a/src/components/slider/slider.js +++ b/src/components/slider/slider.js @@ -269,7 +269,9 @@ function SliderDirective($$rAF, $window, $mdAria, $mdUtil, $mdConstant, $mdThemi } function stepValidator(value) { if (angular.isNumber(value)) { - return Math.round(value / step) * step; + var formattedValue = (Math.round(value / step) * step); + // Format to 3 digits after the decimal point - fixes #2015. + return (Math.round(formattedValue * 1000) / 1000); } } diff --git a/src/components/slider/slider.spec.js b/src/components/slider/slider.spec.js index 9897aa120c8..dcdc19022fd 100644 --- a/src/components/slider/slider.spec.js +++ b/src/components/slider/slider.spec.js @@ -24,12 +24,12 @@ describe('md-slider', function() { $rootScope.$apply('value = 50'); slider.triggerHandler({type: '$md.pressdown', pointer: { x: 30 }}); - slider.triggerHandler({type: '$md.dragstart', pointer: { x: 30 } }); + slider.triggerHandler({type: '$md.dragstart', pointer: { x: 30 }}); $timeout.flush(); expect($rootScope.value).toBe(30); //When going past max, it should clamp to max - slider.triggerHandler({type: '$md.drag', pointer: { x: 150 } }); + slider.triggerHandler({type: '$md.drag', pointer: { x: 150 }}); $timeout.flush(); expect($rootScope.value).toBe(100); @@ -194,5 +194,36 @@ describe('md-slider', function() { }); expect(slider).not.toHaveClass('active'); })); + + it('should increment at a predictable step', inject(function($rootScope, $timeout) { + + buildSlider(0.1, 1).drag({x:70}); + expect($rootScope.value).toBe(0.7); + + buildSlider(0.25, 1).drag({x:45}); + expect($rootScope.value).toBe(0.5); + + buildSlider(0.25, 1).drag({x:35}); + expect($rootScope.value).toBe(0.25); + + buildSlider(1, 100).drag({x:90}); + expect($rootScope.value).toBe(90); + + function buildSlider(step, max) { + var slider = setup('ng-model="value" min="0" max="' + max + '" step="' + step + '"'); + $rootScope.$apply('value = 0.5'); + + return { + drag : function simulateDrag(drag) { + + slider.triggerHandler({type: '$md.pressdown', pointer: drag }); + slider.triggerHandler({type: '$md.dragstart', pointer: drag }); + + $timeout.flush(); + } + }; + } + + })); });