Angular: Keeping attributes with invalid values in an ngModel

Posted . Visible to the public.

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

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

Last edit
Besprechungs-PC
License
Source code in this card is licensed under the MIT License.
Posted to makandra dev (2014-12-11 13:20)