$ parsers and $ formatters are called only once, and not every time the value is updated

I am trying to create a directive with a name currencythat adds $up to text input. The dollar sign must always be displayed and cannot be deleted.

Here is my code:

app.directive('currency', function() {
    return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, elem, attrs, controller) {

      // view -> model
      controller.$parsers.push(function (viewValue) {
        viewValue = viewValue.replace(/^\$/, '');
        controller.$viewValue = viewValue;
        return viewValue;
      });

      // model -> view
      controller.$formatters.push(function (modelValue) {
        modelValue = '$' + modelValue;
        controller.$modelValue = modelValue;
        return modelValue;
      });
    }
  };
});

Working example: https://jsfiddle.net/U3pVM/29012/

As you can see, the dollar sign is added initially, but can be deleted and will not be added after that. It seems that the function that I click on $formattersis called only once. Should this work like that, or am I missing something? How can I implement the desired behavior?

+4
source share
2

ok, , , , .

: https://jsfiddle.net/U3pVM/29014/

controller.$parsers.push(function (viewValue) {
      //console.log(viewValue.substring(0,1));

      if(viewValue.substring(0,1) != "$"){
            var view_value = "$" + viewValue;
          controller.$setViewValue(view_value);
          controller.$render();
      }
        viewValue = viewValue.replace(/^\$/, '');
        //controller.$viewValue = viewValue;


        console.log(viewValue);
        return viewValue;
      });

P.S: , ngModel controller link . .

+2

, , $ $formatters. , - , $ . Formatters .

, ($ formatter), - - ( $parser).

, , , $parsers $formatters, . ( ), , , , , .

Edit

. , , :

link: function (scope, elem, attrs, controller) {

  elem.bind('keyup', function(evt) {
     // Change the displayed value after every keypress
     // This function is an example and needs serious work...
     // Perhaps you should even put this in a separate directive
     var value = elem.val().replace(/[^$0-9]/g, '');
     if (value && value.substring(0,1) !== '$') {
        value = '$' + value;
     }
     elem.val(value);
  });

  // view -> model
  controller.$parsers.push(function (viewValue) {
    // Any time the view changes, remove the $ sign and interpret the rest as number for the model
    var modelValue = viewValue.replace(/^\$/, '');
    return parseFloat(modelValue);
  });

  // model -> view
  controller.$formatters.push(function (modelValue) {
    // Any time the model (number) changes, append it with a $ sign for the view
    var viewValue = '$' + modelValue;
    return viewValue;
  });
}

: https://jsfiddle.net/cL0hpvp4/

+2

Source: https://habr.com/ru/post/1664397/


All Articles