0

Working with the latest version of Angular.

I have a directive when I am setting a custom validator and also monitoring the ngModel for changes. $scope.$watch is only working when the validator returns true and not when it returns false. I'm curious why this is and what the alternative is.

The goal is that the validator should set the form to be valid when the right conditions are met. The $scope.watch() is intended to do additional text formatting as the user is typing, i.e. only allowing number inputs for example.

app.directive('validatorDirective', [
  function ($timeout) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function ($scope, $element, $attr, $controller) {

        $scope.$watch($attr.ngModel, function (val) {
          // no output when validator returns false, but returns model updates when validator returns true
          console.log(val);
        });

        $controller.$validators.validFn = function (modelValue, viewValue) {
          return false;
        };
      }
    }
  }
}]);
Geuis
  • 41,122
  • 56
  • 157
  • 219

1 Answers1

2

In Angular ng-model values are null when the validation fails. My assumption is that this is causing your problem.

In Angular 1.3 they added ng-model-options to allow invalid values to be set on the model:

<input ng-model="my.value" ng-model-options="{allowInvalid: true}">

I think what might be happening is that once the model becomes invalid, the value never changes. Even though you may continue to type in the input the model value remains null and the watcher doesn't fire.

Sunil D.
  • 17,983
  • 6
  • 53
  • 65
  • That was helpful and answered that specific question. Turns out that what I really wanted to do was do numeric-only filtering and to validate true when a particular sequence pattern was entered. The right way to do that is with $parsers, $formatters, and $validators. This is a good reference too http://stackoverflow.com/questions/14419651/filters-on-ng-model-in-an-input/14425022#14425022 – Geuis Jun 02 '15 at 20:07