Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active January 14, 2016 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save henrik/769d49136744ddcaa1dc to your computer and use it in GitHub Desktop.
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.
# 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
#= 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