Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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