How to start checking ngModel for additional events after initialization

despite using google and so, I haven't found a solution to my problem. Thanks for watching.

I want to implement the following input validation behavior (using angular ngModelController):

Input validation should only run after the user first leaves the field. However, if there are validation errors, validation should be triggered not only on blur, but also on change, so that the user is notified of this when the error is fixed.

I created a directive with only a (post) link function that "requires" s ngModel in the same element.

angular.module('foo').directive('errFB', function(){
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, iElem, attrs, ngModel){
          // which trigger source / event should I listen on?
          // iElem.on, ngModel.$viewChange, scope.$on, scope.$parent.$on?
          // iElem.on, seemed the best fit.
          xyz.on(..., function(){

            if (ngModel.$touched && ngModel.$invalid){
                // here validation is not triggered.
                // probably, due to having ngModelOptions
                // set to only validate on blur?
                // could this be changed programmatically?
                ngModel.$validate();
            }
          }
        }
    }
});

      

for the second comment regarding trigger checking: I thought doing it the other way around: that is, first enable checking with ngModelOptions both by default and by blur, and then stop performing the check in case it is caused by the "default" trigger when ngModel. === false. But disabling validation seems very tricky and goes against angular flow.

Any suggestions are greatly appreciated. Many thanks!

+3


source to share


1 answer


So, after a lot of hard trying, I found a way. It's actually quite simple:

link: function(scope, iElem, attrs, ngModel){
    iElem.on("change", function(evt){
        if (ngModel.$touched && ngModel.$invalid){
            ngModel.$options.updateOnDefault = true;
            ngModel.$validate();
        }
 });

      



As you can see the model. The $ options (which define the events on which the modelController $ validation pipeline runs) can be set after the create / run time. A call to check will result in a check queue (which will run on the next check event).

+7


source







All Articles