In AngularJS $formatters are array of functions to execute, as a pipeline, whenever the model value changes. The functions are called in reverse array order, each passing the value through to the next. The last return value is used as the actual DOM value. Used to format / convert values for display in the control. Formatters will NOT be called when the model is changed in the view. For example, you can continue to type lower case letters into the input and your formatters will not be called. Formatters are only called when the model changes in code.

Difference between parsers and formatters are the way in which changes are propagated between view and model:

Parsers: view -> model
Formatters: model -> view

Let’s take a scenario where the model needs to be modified (toUpperCase) on click of a button
View it in Plunker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>AngularJS Form Example</title>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script>
        angular.module('myApp', []).directive('upperCase', function () {
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function (scope, element, attrs, modelCtrl) {
                    modelCtrl.$formatters.push(function (inputValue) {
                        return inputValue.toUpperCase();
                    });
                }
            };
        });
    </script>
  </head>
  <body>
    <input type="text" ng-model="user.name" upper-case />
    <input type="button" value="UpCase" ng-click="user.name='convert to upper case'"/>
  </body>
 
</html>
“Keep learning.”
-Rushi

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>