rob rob - 4 months ago 14
AngularJS Question

Can't enter invalid view value when using ng-model-optios getterSetter

If I am using

ng-model-option
's
getterSetter
with form validation then I cannot enter anything invalid into an input. e.g.

HTML

<input type="number" ng-model-options="{getterSetter: true}" ng-model="ctrl.myVal" min="10">


JS

this.myVal = function(value) {
if (value !== undefined) {
this.actualVal = value;
} else {
return this.actualVal;
}
};


https://plnkr.co/edit/dUPXiD1elGfqZSf9x9Bk?p=preview

With that input I cannot enter any number as it would be less than 10.

I am trying to get the same behavior I get without the
getterSetter
. Namely: a user can enter any invalid input in the view but the model will only be set when the input is valid.

Anyone know a workaround I can user to get form validation working with a
getterSetter
or can anyone explain why this is happening?

Answer

This happens because the value passed to your setter can be undefined, tricking your getterSetter into handling a "setter" call as "getter" call.

Changing your condition from value !== undefined to arguments.length will fix your issue: Updated plnkr

Comments