Parser function not called to change input text field

I am new to parsers and formatters. I have a directive that will do validation when the model changes. One way to do this is $ watch, but from what I understand, this is not very good, since it allows you to update the model.

So, I looked at the parsers and tried this code

app.directive('myDirective', function($compile) {


return {
    restrict: 'E',
    require: 'ngModel',
    scope: {

    },

    link: function($scope, elem, attr, ctrl) {
      console.debug($scope);
      ctrl.$formatters.push(function(value) {
        console.log("hello1");
        return value;
      });
      ctrl.$parsers.unshift(function(value) {

        debugger;
        console.log("hello");
        return value;
      });
    }
  };
});

But the parser function is never called. Formatting is called once. Please see plunkr . Someone tell me what I'm doing wrong, why the parser function does not receive the call when I enter a text field?

+4
source share
2 answers

, : , , "", $parsers, ui . :

app.directive('myDirective', function($compile) {

return {
    restrict: 'E',
    require: 'ngModel',
    scope: {

    },

    link: function($scope, elem, attr, ctrl) {
      console.debug($scope);
      ctrl.$formatters.push(function(value) {
        console.log("hello1");
        return value;
      });
      ctrl.$parsers.unshift(function(value) {
        return value;
      });
      scope.$watch('directive model here', function() {
        ctrl.$setViewValue(<build model from view here>);
      });
    }
  };
});

. () .

+1

link , DOM , . :

HTML:

This scope value <input ng-model="name" my-directive>

JS:

app.directive('myDirective', function($compile) {
    return {
        require: 'ngModel',
        link: function($scope, elem, attr, ctrl) {
            ctrl.$parsers.unshift(function(value) {
                console.log("hello");
            });
        }
    };
});

. , link.

0

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


All Articles