Skip to content

Instantly share code, notes, and snippets.

@neilmaledev
Last active July 14, 2016 03:13
Show Gist options
  • Save neilmaledev/675cd4bbaf299e099f2fd253f4610244 to your computer and use it in GitHub Desktop.
Save neilmaledev/675cd4bbaf299e099f2fd253f4610244 to your computer and use it in GitHub Desktop.
.directive('intnum', function () {
return {
require: 'ngModel',
restrict: 'A',
scope: {
intnum: '='
},
link: function (scope, elem, attr, ctrl) {
elem.bind('change', function() {
var value = isNaN(parseInt(ctrl.$viewValue)) ? 1 : parseInt(ctrl.$viewValue);
var min, max, newValue;
if(scope.intnum !== undefined) {
if(scope.intnum.hasOwnProperty('min') && scope.intnum.hasOwnProperty('max')) {
var minimum = parseInt(scope.intnum.min);
var maximum = parseInt(scope.intnum.max);
min = minimum > maximum ? maximum : minimum;
max = maximum < minimum ? minimum : maximum;
if(!isNaN(min) && !isNaN(max)) {
if(value < min) {
value = min;
} else if(value > max) {
value = max;
}
} else if (isNaN(min) && !isNaN(max)) {
if(value > max) {
value = max;
}
} else if (isNaN(max) && !isNaN(min)) {
if(value < min) {
value = min;
}
}
} else if (scope.intnum.hasOwnProperty('min')) {
min = parseInt(scope.intnum.min);
if(!isNaN(min) && value < min) {
value = min;
}
} else if (scope.intnum.hasOwnProperty('max')) {
max = parseInt(scope.intnum.max);
if(!isNaN(max) && value > max) {
value = max;
}
}
}
ctrl.$setViewValue(value.toString());
ctrl.$render();
});
}
};
});
@neilmaledev
Copy link
Author

neilmaledev commented Jul 12, 2016

<input ng-model="age" type="text" class="form-control" intnum="{min: 1}" required />

intnum
intnum=""
intnum="{min: 1}"
intnum="{min: 1, max: 5}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment