Angular: $scope.$watch($ attrs . ngmodel)只在指令的验证器返回true时起作用

Angular: $scope.$watch($attr.ngModel) only working when validator returns true in directive

本文关键字:验证 指令 true 起作用 返回 watch scope attrs ngmodel Angular      更新时间:2023-09-26

使用最新版本的Angular。

当我在设置自定义验证器并监控ngModel的变化时,我有一个指令。美元的范围。$watch只在验证器返回true时工作,而在返回false时不工作。我很好奇为什么会这样,还有什么替代方案。

目标是验证器应该在满足适当条件时将表单设置为有效。$scope.watch()用于在用户输入时进行额外的文本格式化,例如,只允许数字输入。

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

在Angular中,当验证失败时,ng-model的值是null。我认为这是造成你的问题的原因。

在Angular 1.3中,他们添加了ng-model-options来允许在模型上设置无效的值:

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

我认为可能发生的情况是,一旦模型失效,值永远不会改变。即使您可以继续键入输入,模型值仍然为空,并且监视器不会触发。