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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)