angularjs - 在AngularJS中动态更新 'max'验证

标签 angularjs validation min

编辑:大规模简化以达到问题的核心

在 Angular (v1.2.22) 验证中,如果 max 的值取决于另一个值,并且该值更新,则验证状态不会自动更新。

var app = angular.module('app',[]).
controller('TestCtrl', function($scope){
  $scope.partWidth = 10;
});

HTML:

<form name="itemForm">
  <label for="partWidth">Part width</label>
  <input id="partWidth" name="partWidth" min="10" max="180"  ng-model="partWidth" placeholder="mm" required type="number">

  <label for="cutterwidth">Cutter width</label>
  <input id="cutterwidth" name="cutterwidth" min="10" max="{{ partWidth }}"  ng-model="cutterwidth" placeholder="mm" required type="number">
</form>

更新了 Plunker http://plnkr.co/edit/lNemYyFrHF9gyRgY8KIT

除非 cutterwidth 本身被编辑,否则 ng-invalid 类不会被删除。

a) 这是一个错误吗?

b) 有解决方法吗? (例如强制运行验证,以某种方式触发输入事件等)

最佳答案

a) 我认为是this bug .

b) 经过多次史诗般的战斗后,我的解决方法是完全避免使用 native max 属性,而是构建一个自定义指令。

我将 ngAppMax 属性公开给范围,并使用 = 传入 ngModel。我不完全理解这一点,但它确实有效。

然后,我比较这两个值并在模型(名为“ctrl”)上使用 $setValidity

Here's a working Plunker ,或参见下文:

HTML

<form name="itemForm">
  <input name="partWidth" min="10" max="300" ng-model="partWidth" placeholder="mm" required type="number">
  <input name="cutterwidth" min="10" ng-app-max="{{ partWidth }}" ng-model="cutterWidth" placeholder="mm" required type="number">
</form>

JS

angular.module('app',[]).
controller('TestCtrl', function($scope){}).
directive('ngAppMax', function(){
  return {
    require: 'ngModel',
    scope: {
      ngAppMax: '@',
      ngModel: '='
    },
    link: function(scope, element, attrs, ctrl){

      scope.$watch('ngAppMax', function(newVal){
        validate(scope.ngModel, newVal, ctrl);
      });

      scope.$watch('ngModel', function(val){
        validate(val, scope.ngAppMax);
      });

      function validate(thisVal, maxVal){
        if(thisVal > maxVal){
          ctrl.$setValidity('range', false);
        } else {
          ctrl.$setValidity('range', true);
        }
      }

    }
  }
});

关于angularjs - 在AngularJS中动态更新 'max'验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25407944/

相关文章:

javascript - 在 Joi 验证中忽略 "required"?

javascript - 正则表达式验证范围内的日期年份

MySQL获取选择行的最大值和最小值之间的差异

javascript - 预先检查的输入框未被序列化

c# - Angular Web 应用程序数据绑定(bind)不起作用

javascript - AngularJS 使用参数创建部分模板

validation - Podspec 无法通过验证,但没有记录错误

mysql - MIN() 日期时间记录检索 - MySQL

sql-server-2008 - T-SQL : Finding the closest location of an object on a map grid

angularjs - Angular Material : Custom md-tab-label in md-tabs