sne11ius sne11ius - 6 months ago 27
AngularJS Question

Get "raw" value from invalid input field

I have an input field in a form with some validations. It works like a charm.

It basically looks like this:

<input
class="form-control"
type="number"
ng-model="zipcode"
ng-minlength="5"
ng-maxlength="5"
id="zipcode"
name="zipcode"
required
>


A working plunkr is here: http://plnkr.co/edit/H0h59kG75T5MGE9cAhSo?p=preview

But now I also want to react to every input change - whether valid or not. So for example if the input field contains "123" it is not valid and the value is not transferred to my model - thats fine. But I still want to get the value to do some intermediate requests to a webservice.

Any Ideas?

Answer

Here is what i came up with for your scenario.

Basically you can write a directive which requires ngModel (ngModelController). The ngModelController has a array of parsers which it call to parse the view value in a pipeline manner. If validation fail these parsers do not update the model. If you inject a custom parser at the start of this parsers array, you can get the each view change value and do anything you want with it.

See my plunkr here http://plnkr.co/edit/ruB42xHWj7dBxe885OGy?p=preview (See console)

The basic code would be

ngModelCtrl.$parsers.splice(0,0,(function (viewValue) {
              console.log("The view value is:"+viewValue)
                return viewValue;           
            }));

Also see ngModelController documenation