ngModel Formatters and Parsers

This topic was covered really well in a related question: How to do two-way filtering in AngularJS?

To summarize:

  • Formatters change how model values will appear in the view.
  • Parsers change how view values will be saved in the model.

Here is a simple example, building on an example in the NgModelController api documentation:

  //format text going to user (model to view)
  ngModel.$formatters.push(function(value) {
    return value.toUpperCase();
  });

  //format text from the user (view to model)
  ngModel.$parsers.push(function(value) {
    return value.toLowerCase();
  });

You can see it in action: http://plnkr.co/UQ5q5FxyBzIeEjRYYVGX?plnkr=legacy

<input type="button" value="set to 'misko'" ng-click="data.name="misko""/>
<input type="button" value="set to 'MISKO'" ng-click="data.name="MISKO""/>
<input changecase ng-model="data.name" />

When you type a name in (view to model), you will see that the model is always lowercase. But, when you click a button and programatically change the name (model to view), the input field is always uppercase.

Leave a Comment