Reputation: 2190
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.
Upvotes: 4
Views: 378
Reputation: 2148
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":""}
Upvotes: 1
Reputation: 1519
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
Upvotes: 5
Reputation: 4156
If the result would be user = {}
, then it would mean that Angular would have to actually delete
that property entirely, by calling user.delete('last'), which is something it can not do. It does not know anything about person
object. It only got reference to the person.last
property
Upvotes: 0