简体   繁体   English

用于范围验证的Angular指令

[英]Angular directive for range validation

I am trying to make a directive for an input to limit the value between 1-99 . 我正在尝试为input设置指令以将值限制在1-99之间。 On the same input I also have another directive that converts the value to a percentage and am not sure if that is what is getting in the way. 在同一输入上,我还具有另一个指令,该指令将值转换为百分比,并且不确定这是否会成为问题。

The directive is simple (taken basically from the Angular website): 该指令很简单(基本上从Angular网站获取):

(function() {
  'use strict';

  angular
    .module('app.model')
    .directive('inputRange', inputRange);

  function inputRange() {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function(scope, elm, attrs, ctrl) {
        var INTEGER_REGEXP = /^-?\d+$/;
        ctrl.$validators.inputRange = function(modelValue, viewValue) {
          if (ctrl.$isEmpty(modelValue)) {
            // consider empty models to be valid
            return true;
          }

          if (INTEGER_REGEXP.test(viewValue)) {
            // it is valid
            return true;
          }

          // it is invalid
          return false;
        };
      }
    }
  }
});

And the section of html with the input field (which is paired with a slider): 以及带有输入字段(与滑块配对)的html部分:

  <form name="form">
    <div sc-slider
        ng-model="vm.baseline"
        min="0.01"
        max="0.99"
        initial="{{vm.baseline}}"
        step="0.01"
        uib-tooltip="The initial estimate of the KIQ's likelihood - prior to any indicator observations."

        tooltip-popup-delay="200"
        tooltip-popup-close-delay="200"
        tooltip-placement="bottom"></div>
    <input to-percent
        input-range
        name="baseline"
        style="text-align:center;"
        type="text"
        min="1"
        max="99"
        class="form-control"
        ng-model="vm.baseline"></input>
    <span ng-show="form.baseline.$error.inputRange">The value is not a valid integer!</span>
    <span ng-show="form.baseline.$error.min || form.baseline.$error.max">
      The value must be in range 1 to 99!</span>
  </form>

I have read on SO about priority for directives that share an input but I don't think that is necessarily an issue here. 我已经阅读了关于共享输入的指令的优先级的信息,但我认为这不一定是一个问题。 But when I enter a value greater than 99 I'd expect one of the spans below to show up, but nothing is appearing. 但是,当我输入一个大于99的值时,我期望下面的跨度之一出现,但是什么也没有出现。 And my other directive works fine all of the time. 我的其他指令一直都可以正常工作。 Any help is appreciated. 任何帮助表示赞赏。

使您的生活更轻松,并在输入元素上使用ng-maxng-min属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM