Read more

Angular: Keeping attributes with invalid values in an ngModel

Thomas Klemm
December 11, 2014Software engineer

The Angular 1.2 way:

# By default, angular returns undefined for invalid attributes which removes
# the value from the form field's ngModel (which means it's not sent to the
# server, and old values would not be overwritten).
#
# This directive makes sure that form fields with an invalid value return an
# empty string instead of undefined.

for elementType in ['input', 'textarea', 'select']
  @app.directive elementType, ->

    priority: 1
    restrict: 'E'
    require: '?ngModel'

    link: (scope, element, attributes, ngModelController) ->
      return unless ngModelController

      if elementType == 'input'
        inputType = angular.lowercase(attributes.type)
        return if inputType == 'radio' || inputType == 'checkbox'

      ngModelController.$parsers.push (value) ->
        if ngModelController.$invalid && !value?
          ''
        else
          value

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

In Angular 1.3, there's an allowInvalid option Show archive.org snapshot to allow invalid model values to be written to the ngModel.

Posted by Thomas Klemm to makandra dev (2014-12-11 14:20)