【问题标题】:Custom directive for form validation用于表单验证的自定义指令
【发布时间】:2014-12-26 15:31:50
【问题描述】:

我正在尝试通过angularJS 根据其最小值和最大值验证一个数字 这是自定义指令,我首先尝试使用为输入数字验证提供 angularJs 的 max,它适用于静态数字而不是绑定数据。这就是我考虑自定义指令的原因

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

在视图中:

<div class="modal-body" >
    title: {{book.title}}<br>
    price: {{book.price}}<br>
    quantity: {{book.nbr_exemplaires}}
    <form name= "myForm" ng-submit= "addToCart(book, quantity, <%= current_user.id %>)" novalidate >
      <input type="number" min="1"  ng-max="{{book.nbr_exemplaires}}" name= "quantite" ng-model="quantity" required  >
      <span style="color:red" ng-show="myForm.quantite.$error.required">
        <span ng-show="myForm.quantite.$error.required">quantity is required!</span>
      </span>


  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button  class="btn btn-primary" ng-disabled="myForm.$invalid ">Save changes</button>
  </div>
  </form>

我不明白问题出在哪里

【问题讨论】:

  • 我会警告您不要使用“NG”前缀:如果您必须升级到 angularJS 10.7,谁会知道他们是否会实施 ngMax 指令?在这种情况下你会遇到一些错误..

标签: angularjs angularjs-directive


【解决方案1】:

为避免出现 X/Y 问题,当您尝试某事但它不起作用时,请先尝试解决该问题。很好,您提供了更广泛的上下文,特别是针对您的问题,内置的 max 提供了您需要的一切:

<input type="number" max="{{max}}" ng-model="foo">

并且可以动态设置max,例如:

$scope.max = 10;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 2017-05-26
    • 2014-03-07
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多