Question

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 ?

Était-ce utile?

La 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.

Autres conseils

Your link function is not called because the associated DOM element is not changing, just the model is. This works:

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

See here for more on when the link function is called.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top