1

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?

2
  • Shoulnd you be using an input type="text" then? And if you want to limit to only numbers, use a proper function for it ? Commented Aug 12, 2016 at 13:56
  • @GustavoGabriel, can you provide a basic example of this? Commented Aug 12, 2016 at 14:00

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

As I know $parsers are used to format data coming from user to server and formatters - from server to user. However, I need that as a user types text changes(the same as filter but for two way binding) which is something like from user to user
@RustamIbragimov, nothing to do with server, they are all about two way binding: $parsers convert the data from the displayed value in the view to the model value, $formatters convert from the model to the value displayed in the view (there was a typo in my example where I wrote $parsers instead of $formatters which I've now corrected)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.