|
| 1 | +/** |
| 2 | + * It might be a bug, but currently input[type=number] does not add |
| 3 | + * a parser, so the model gets populated with a string. It does however stop non numbers so it |
| 4 | + * must have some preproccessing. Anyway, this adds parser before schema-validate hooks into it. |
| 5 | + * FIXME: this is still not a complete solution. Inputting a string in an input[type=number] results |
| 6 | + * in parsers never firing and ngModel value removed. So no validation from schema-validate either. |
| 7 | + */ |
| 8 | +angular.module('schemaForm').directive('sfTypeParser', function() { |
| 9 | + return { |
| 10 | + restrict: 'A', |
| 11 | + scope: false, |
| 12 | + require: 'ngModel', |
| 13 | + link: function(scope, element, attrs, ngModel) { |
| 14 | + var once = scope.$watch(attrs.sfTypeParser, function(schema) { |
| 15 | + if (!schema) { |
| 16 | + return; |
| 17 | + } |
| 18 | + |
| 19 | + var isNumber = schema.type.indexOf('number') !== -1; |
| 20 | + var isInteger = schema.type.indexOf('integer') !== -1; |
| 21 | + var numberRE = /^[0-9]*$/; |
| 22 | + // Use index of since type can be either an array with two values or a string. |
| 23 | + if (isNumber || isInteger) { |
| 24 | + // The timing here seems to work. i.e. we get in before schema-validate |
| 25 | + ngModel.$parsers.push(function(viewValue) { |
| 26 | + var value; |
| 27 | + if (isNumber) { |
| 28 | + value = parseFloat(viewValue); |
| 29 | + } else if (numberRE.test(viewValue)) { |
| 30 | + // We test the value to check that it's a valid integer, otherwise we can easily |
| 31 | + // get float -> integer parsing behind the scenes. |
| 32 | + value = parseInt(viewValue, 10); |
| 33 | + } |
| 34 | + console.log('parser', numberRE.test(viewValue), viewValue, value) |
| 35 | + if (value === undefined || isNaN(value)) { |
| 36 | + //Let the validation fail. @FIXME: it fails with "required" for some reason. |
| 37 | + return viewValue; |
| 38 | + } |
| 39 | + return value; |
| 40 | + }); |
| 41 | + } |
| 42 | + |
| 43 | + once(); |
| 44 | + }); |
| 45 | + } |
| 46 | + }; |
| 47 | +}); |
0 commit comments