Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Behavior Of Angular With TextBox Required

I have 2 textboxes, one which is required and the other one which is not required.

If we add text in the required text box, say "ABC", then remove the content, the ng-model is set to undefined

If we add text to the non required field and remove the content, the ng-model is not to empty string "".

Here is a plunk about the behavior I've explained above. Please use the console to look at the result.

http://plnkr.co/edit/XgQBfcyRF3OwG1qC0gXb?p=preview

Why is there a difference in setting the ng-model between the two?

like image 479
Abilash Avatar asked Jul 12 '13 06:07

Abilash


1 Answers

It is seems to be by design, and has to do with a consistent behavior of validated form values.

There isn't anything on this behaviour in the docs, AFAIK.. It is implied here -> https://github.com/angular/angular.js/blob/master/src/ng/directive/input.js#L1045

With angularJS validation, if a value entered on field is allowed, that becomes the model's value (as any other bound value would behave). If it isn't, the only way to be consistent is to set the value as undefined (as no allowed value is in the field). The two other options would be to keep it's last valid value, or keep binding the wrong value, only triggering the flags for invalid field, and form. Both these solutions are bad - leaving the last value is probably not wanted (if you were to use the values disregarding the state of the form, it would lead to errors) and allowing for invalid values is a terrible sin ;) (you couldn't trust the validation service to help prevent buggy use of wrong types)

Although it may seem strange or even inconsistent, it really isn't. I have slightly modified your plunkr to validate for a number, which I believe makes it clearer why it is this way: http://plnkr.co/edit/9gJmblUn9MUUeFt5lWJZ?p=preview.

So, in reality there is no difference - only in your second input an empty string is considered a valid, thus accepted value for that field.

like image 71
Tiago Roldão Avatar answered Oct 20 '22 04:10

Tiago Roldão