Last active
January 14, 2016 07:14
-
-
Save henrik/769d49136744ddcaa1dc to your computer and use it in GitHub Desktop.
AngularJS directive to disallow non-digits in an input field. Based on http://stackoverflow.com/a/19675023/6962 Done with @tskogberg.
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
# http://stackoverflow.com/a/19675023/6962 | |
app.directive "onlyDigits", -> | |
restrict: "A" | |
require: "?ngModel" | |
link: (scope, element, attrs, ngModel) -> | |
return unless ngModel | |
ngModel.$parsers.unshift (inputValue) -> | |
digits = inputValue.replace(/\D/g, "") | |
ngModel.$viewValue = digits | |
ngModel.$render() | |
digits |
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
#= require helpers/angular_helper | |
#= require directives/only_digits | |
describe "onlyDigits", -> | |
$compile = null | |
$scope = null | |
beforeEach inject (_$compile_, _$rootScope_) -> | |
$compile = _$compile_ | |
$scope = _$rootScope_ | |
it "strips non-digits from the ng-model value (i.e. doesn't let you input them into a form field)", -> | |
formElement = compile """ | |
<form name="theForm"> | |
<input name="theField" ng-model="foo" only-digits> | |
</form> | |
""" | |
inputElement = formElement.find("input") | |
inputModel = $scope.theForm.theField | |
inputModel.$setViewValue("123abc") | |
expect(inputElement.val()).toEqual("123") | |
compile = (html) -> | |
element = $compile(html)($scope) | |
$scope.$digest() | |
element |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment