Here is my custom Angular JS Directive to ensure user input is within the valid number range. The code works like this:
- The user input is parsed by a regex expression to ensure that only digits are allowed.
- Once it gets parsed, it will check if the value is within the number range specified using range-min and range-max attributes.
- If it is below the range minimum, set the ngModel value to the range minimum value.
- If it is more than the range maximum, set the ngModel value to the range maximum value.
Here is the Javascript code for the directive.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
module.directive('range', function() { return { restrict: 'A', require: '?ngModel', link: function (scope, element, attrs, ngModel) { if (!ngModel) return; ngModel.$parsers.push(function(val) { var parsed = val.replace(/[^0-9]+/g, ''); if (parseInt(parsed) > parseInt(attrs.rangeMax)) parsed = attrs.rangeMax; if (parseInt(parsed) < parseInt(attrs.rangeMin)) parsed = attrs.rangeMin if (val !== parsed) { ngModel.$setViewValue(parsed); ngModel.$render(); } return parsed; }); } }; }); |
And here is the sample HTML code.
|
1 |
<input type="text" range range-min="1" range-max="100"/> |
A good case scenario to apply this directive is for input fields for percentage where 1-100 is your number range.