Last active
August 29, 2015 14:18
-
-
Save nklatt/17a9a62297ae277550d9 to your computer and use it in GitHub Desktop.
Extending Angular number inputs to validate for step attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular | |
.module('myApp', []) | |
.directive("step", function() { | |
return { | |
restrict: "A", | |
require: "ngModel", | |
link: function(scope, element, attributes, ngModelCtrl) { | |
ngModelCtrl.$validators.step = function(modelValue, viewValue) { | |
var isValid = true; // assumed innocent until proven guilty | |
if ( ! ngModelCtrl.$isEmpty(modelValue) ) { // empty is okay | |
var $element = $(element); // jQuery? that's lame, you hack | |
var value = parseFloat($element.val()); | |
var min = $element.attr("min") || 1; | |
var max = $element.attr("max") || value; | |
if ( value // don't flag value of zero | |
&& value >= min // only flag increment if they've met the minimum | |
&& value <= max ) { // only flag increment if they've met the maximum | |
var step = $element.attr("step") || 1; | |
if (value % step) { | |
isValid = false; | |
} | |
} | |
} | |
return isValid; | |
} | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment