I'm using ngMessages in my form. I have one field I want the user to be able to insert digits only. If the user type some letters that are not numbers (e.g not 0-9) nothing will be shown in the field. In addition, I want to use ng-min and ng-max to validate the inserted value. So I created a directive but in order to use ng-min and ng-max I need to use "type=number" which ruins my directive behavior...
This is the field from my form:
<div class="field">
<label for="age">insert your age</label>
<input name="age"
ng-model="data.age"
ng-minlength="1"
ng-maxlength="2"
ng-min="10"
ng-max="80"
only-digits
type="number"
required/>
<div class="error-messages" ng-messages="userForm.age.$error">
<div ng-message="required">You left the field blank...</div>
<div ng-message="minlength">Your field is too short</div>
<div ng-message="maxlength">Your field is too long</div>
<div ng-message="min">You must be at least 10 years old!</div>
<div ng-message="max">You must be less than 80 years old!</div>
</div>
</div>
And my directive is:
angular.module('directives').
directive('onlyDigits', function () {
return {
restrict: 'A',
require: '?ngModel',
scope: {
},
link: function (scope, element, attrs, ngModel) {
if (!ngModel) return;
ngModel.$parsers.unshift(function (inputValue) {
var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s != ' '); }).join('');
ngModel.$setViewValue(digits, "");
ngModel.$render();
return digits;
});
}
};
});