Reputation: 42277
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;
};
}
}
}
}]);
Upvotes: 0
Views: 256
Reputation: 18193
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.
Upvotes: 2