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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)