如果稍后更改值,则最小/最大验证不起作用

har*_*shr 7 angularjs

我有一个要求,其中一个字段的最小值取决于另一个字段中给出的输入.

<input type="number" name="minval" class="form-control" ng-model="user.minval" 
      ng-required="true">
Run Code Online (Sandbox Code Playgroud)

此输入用于验证另一个字段

<input type="number" name="inputval" class="form-control" ng-model="user.inputval" 
     ng-required="true" min="{{user.minval}}">
Run Code Online (Sandbox Code Playgroud)

但这没有按预期工作..如果我稍后改变"minval"输入没有得到重新验证..

我已经尝试从JS中设置min的初始值,正如在某些解决方案中所建议的那样但这也没有帮助......

PLUNKER LINK

小智 8

使用ng-min/ng-max指令

app.directive('ngMin', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attr, ctrl) {
            scope.$watch(attr.ngMin, function(){
                if (ctrl.$isDirty) ctrl.$setViewValue(ctrl.$viewValue);
            });

            var isEmpty = function (value) {
               return angular.isUndefined(value) || value === "" || value === null;
            }

            var minValidator = function(value) {
              var min = scope.$eval(attr.ngMin) || 0;
              if (!isEmpty(value) && value < min) {
                ctrl.$setValidity('ngMin', false);
                return undefined;
              } else {
                ctrl.$setValidity('ngMin', true);
                return value;
              }
            };

            ctrl.$parsers.push(minValidator);
            ctrl.$formatters.push(minValidator);
        }
    };
});

app.directive('ngMax', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, elem, attr, ctrl) {
            scope.$watch(attr.ngMax, function(){
                if (ctrl.$isDirty) ctrl.$setViewValue(ctrl.$viewValue);
            });
            var maxValidator = function(value) {
              var max = scope.$eval(attr.ngMax) || Infinity;
              if (!isEmpty(value) && value > max) {
                ctrl.$setValidity('ngMax', false);
                return undefined;
              } else {
                ctrl.$setValidity('ngMax', true);
                return value;
              }
            };

            ctrl.$parsers.push(maxValidator);
            ctrl.$formatters.push(maxValidator);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案首先出现在此处:http://stackoverflow.com/questions/15656617/validation-not-triggered-when-data-binding-a-number-inputs-min-max-attributes注意ng-min和ng-max现在支持Angular而无需编写自己的指令. (4认同)
  • 说真的?,你想用手表吗?... http://angular-tips.com/blog/2013/08/removing-the-unneeded-watches/ (2认同)