Angular seems to have a different behavior when a user enters and then clears text in an input field depending if this field is required or not.
Take a look at this example. By default the model is user = {"name":"guest","last":"visitor"}. When clearing both fields the model becomes user = {"last":""} whereas I would have expected user = {}.
Why is this the case? And, is there a way to get the same behavior for both fields without making them both (not) required?
Update:
I used a workaround with watch in the end:
$scope.$watch('user',function(newValue) {
for (var prop in newValue) {
if (newValue.hasOwnProperty(prop)){
if (newValue[prop] !== undefined && newValue[prop] == "")
newValue[prop] = undefined;
}
}
}, true);
Most likely the last if-condition could be written more efficiently, but at least it seems to work as expected.
When there's an error in validation, the model is set to undefined hence the disappearing name key (which is validated with required).
It's a known bug in Angular that an empty field with ng-minlength does not get invalidated correctly. If you set the value to a (which is still 2 letters short of minimum 3) you'll notice both keys disappear correctly.
https://github.com/angular/angular.js/issues/7277
This situation creates because "User Name:" field has required validation ,so when you clear "User Name:" field. "User Name:" field doesn't pass the required validation. As a result, the model becomes user = {"last":""}
On the other hand, "Last name:" has ng-minlength="3" and ng-maxlength="10" validation so, after clear "Last Name:" field when you enter 1 or 2 character on "Last Name:" field. It doesn't pass the minlength validation so, the model becomes user = {}
so if any validation fails like "User Name:" field, it vanish from the model and the model becomes user = {"last":""}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With