Rustam Ibragimov
Rustam Ibragimov

Reputation: 2707

Angular display formatted number in input field

guys. I have an input field:

<input type="number" name="price" ng-model="ctrl.form.price" required>

The problem is that whenever a user types digits it automatically formats it. Example: 5 312 000.12313 However, when a user submits this form, the value of ctrl.form.price should be 5312000.12313. I know that there are filters, but as I know they can be used only for one way data binding. Any way to do this?

Upvotes: 1

Views: 2483

Answers (1)

Duncan
Duncan

Reputation: 95652

You should write a directive with a parser and formatter. The parser function should convert from the displayed value with spaces to a number, and the formatter function converts the number to the displayed text.

Something like:

angular.module('app').directive('formattedNumber', formattedNumber);

function formattedNumber() {
   var directive = {
        restrict: 'A',
        require 'ngModel',
        link: link
   };
   return directive;

   function link(scope, element, attrs, ngModelController) {
       ngModelController.$parsers.push(parseNumber);
       ngModelController.$formatters.push(formatNumber);
   }

   function parseNumber(viewValue) {
       // convert text with spaces to number and return it.
   }
   function formatNumber(modelValue) {
       // convert numeric modelValue to formatted text and return it.
   }
}

Then just:

<input type="number" name="price" ng-model="ctrl.form.price"
  formatted-number required>

Upvotes: 2

Related Questions