Skip to content

Commit 23d0bac

Browse files
committed
fix(input): format numeric string model values correctly
Previously, when a numeric string is used as a model value, the number input type would not format the value. This patch corrects this behaviour by converting to a number before performing validation, if the value is a string and not NaN. Closes angular#6683
1 parent 79592ce commit 23d0bac

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/ng/directive/input.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1160,6 +1160,9 @@ function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
11601160
}
11611161

11621162
ctrl.$formatters.push(function(value) {
1163+
if (isString(value) && !isNaN(value)) {
1164+
value = Number(value);
1165+
}
11631166
return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
11641167
});
11651168
}

test/ng/directive/inputSpec.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1538,6 +1538,54 @@ describe('input', function() {
15381538
});
15391539

15401540

1541+
it('should translate numeric base-10 strings in model to numbers', function() {
1542+
compileInput('<input type="number" ng-model="age" />');
1543+
1544+
scope.$apply(function() {
1545+
scope.age = '10';
1546+
});
1547+
1548+
expect(scope.age).toBe('10');
1549+
expect(inputElm.val()).toBe('10');
1550+
});
1551+
1552+
1553+
it('should translate numeric base-16 strings in model to numbers', function() {
1554+
compileInput('<input type="number" ng-model="age" />');
1555+
1556+
scope.$apply(function() {
1557+
scope.age = '0xFf';
1558+
});
1559+
1560+
expect(scope.age).toBe('0xFf');
1561+
expect(inputElm.val()).toBe('255');
1562+
});
1563+
1564+
1565+
it('should translate scientific notation from numeric strings in model to numbers', function() {
1566+
compileInput('<input type="number" ng-model="age" />');
1567+
1568+
scope.$apply(function() {
1569+
scope.age = '0.1e6';
1570+
});
1571+
1572+
expect(scope.age).toBe('0.1e6');
1573+
expect(inputElm.val()).toBe('100000');
1574+
});
1575+
1576+
1577+
it('should remove leading zeros from numeric strings in model', function() {
1578+
compileInput('<input type="number" ng-model="age" />');
1579+
1580+
scope.$apply(function() {
1581+
scope.age = '010';
1582+
});
1583+
1584+
expect(scope.age).toBe('010');
1585+
expect(inputElm.val()).toBe('10');
1586+
});
1587+
1588+
15411589
describe('min', function() {
15421590

15431591
it('should validate', function() {

0 commit comments

Comments
 (0)