title: AngularJS number format filter directive for input using NgModel
body: <p>I would like to create a directive for an input control that formats a number with X number of decimal places when the input doesnt have focus.  When the input does have focus, i would like the number to appear unformatted (no commas).</p>
  
  <p>I am almost there, with the following code.  When you click inside the input, the text changes and when you click out (blur event) the text formats again.  However, if i change the value in the input, then the events seem to change round, and the blur event does nothing. Then if you click in the input box again, the value formats when it shouldnt, and the blur event unformats, when it should format.</p>
  
  <p>To use the directive you can simply do</p>
  
  <pre><code>&lt;input number-format ng-model="myValue" decimals="numberOfDecimals" /&gt;
  </code></pre>
  
  <p>Here is the directive</p>
  
  <pre><code>App.directive('numberFormat', ['$filter', '$parse', function ($filter, $parse) {
      return {
          require: 'ngModel',
          link: function (scope, element, attrs, ngModelController) {
              var decimals = $parse(attrs.decimals)(scope);
  
              ngModelController.$parsers.push(function (data) {
                  //convert data from view format to model format
                  return $filter('number')(data, decimals); //converted
              });
  
              ngModelController.$formatters.push(function (data) {
                  //convert data from model format to view format
                  return $filter('number')(data, decimals); //converted
              });
  
              element.bind('focus', function () {
                  element.val(ngModelController.$modelValue);
              });
  
              element.bind('blur', function () {
                  element.val(ngModelController.$viewValue);
              });
          }
      }
  }]);
  </code></pre>