7

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?

4
  • I've tried with v1.0.1, v1.0.7 and v1.1.5. All of them have the same behavior
    – Abilash
    CommentedJul 12, 2013 at 6:17
  • 3
    By default, the value of an empty input is an empty string. Looking through the source, the required attribute hooks into angular's validation, which perhaps returns a new invalid property of the model which is undefined. Good question. I hope you get a real answer!
    – rGil
    CommentedJul 12, 2013 at 7:11
  • Yes, looks this is by design.
    – Paul Chen
    CommentedJul 12, 2013 at 7:17
  • @rGil yes it is the setValidity method is the one that is returning undefined. I wanted to know the real reason why this is sent. Probably because this is used else where to do some validations for required not required.
    – Abilash
    CommentedJul 12, 2013 at 7:20

1 Answer 1

2

It isseems 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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.