Why angular sets undefined to empty ng-model fields Why angular sets undefined to empty ng-model fields angularjs angularjs

Why angular sets undefined to empty ng-model fields


When you have the "required" directive on an input, an empty value will never be set (so it will be undefined).

See the source code ("requiredDirective" in file input.js) where no value is retrieved to store in the model, when the input is blank:

if (attr.required && ctrl.$isEmpty(value)) {   ctrl.$setValidity('required', false);      return;   } else {      ctrl.$setValidity('required', true);      return value;}

IMHO it is a little strange use case anyway: You do want client side validation, but still want to submit invalid values to the server, right?

I guess you can write your own validation ("my-required") to do that.

Alternatively you could copy over default values before posting the data to the server, for example with lodash (or underscore):

_.defaults(formData, { name: ""});


You can configure angular to set your model even when the value is not valid with the property allowInvalid from ngModelOptions.

allowInvalid: boolean value which indicates that the model can be set with values that did not validate correctly instead of the default behavior of setting the model to undefined.

API Reference

Example:

<input    type="text"    ng-model="myvalue"   ng-model-options="{ allowInvalid: true }"/>