javascriptangularjsangularjs-directiveangularjs-model

Parser function does not get called for change in input textbox


I am new to parsers and formatters. I have a directive that will be doing validation on change of the model.One way to do this is the $watch but from what I understand that is not a good way since it allows the model to be updated.

So I was looking at 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. The formatter is called once. Please see the plunkr .Can anyone tell me what I am doing wrong ,why is the parser function not getting called when i type in the textbox ?


Solution

  • This is a late response, but for reference: I think you where missing the "glue" that will call the $parsers while ui changes occurs. This should be something like:

    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>);
          });
        }
      };
    });
    

    For a full reference please see this (awesome) post.