加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何强制执行角度验证指令?

发布时间:2020-12-17 17:37:37 所属栏目:安全 来源:网络整理
导读:我已经为我的表单创建了一个验证指令. 它基本上根据来自另一个字段的数据验证字段值. 它完美无缺:-) 我的问题是,如果在执行验证后其他字段发生更改,则验证将不再运行. var myApp = angular.module('myApp',[]).directive('validateInteger',function() { ret
我已经为我的表单创建了一个验证指令.
它基本上根据来自另一个字段的数据验证字段值.

它完美无缺:-)

我的问题是,如果在执行验证后其他字段发生更改,则验证将不再运行.

var myApp = angular.module('myApp',[])

.directive('validateInteger',function() {
  return {
    require: 'ngModel',link: function(scope,elm,attrs,ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
          var int1val = scope.int1;
          scope.int2valid = (viewValue > int1val) ? "valid" : undefined;
          if (scope.int2valid == "valid") {
              ctrl.$setValidity('higher',true);
              return viewValue;
          } else {
              ctrl.$setValidity('higher',false);
              return undefined;
        }
      });
    }
  };
});

jsfiddle:http://jsfiddle.net/hanspc/vCFFQ/

解决方法

明确引用指令中的某些字段是一个非常糟糕的主意.正如您所看到的,这有许多缺点:不可移植性,代码重复,脆弱性,……

做这样的事情:

<input type="text" ng-model="int2" validate-greater-integer="int1" />

而且:

myApp.directive('validateGreaterInteger',function() {
    return {
    require: 'ngModel',scope: {
        otherInteger : '=validateGreaterInteger',}
    link: function(scope,ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {
        if (viewValue > scope.otherInteger) {
            ctrl.$setValidity('higher',true);
            return viewValue;
        } else {
            ctrl.$setValidity('higher',false);
            return undefined;
        }
    }
});

然后,您可以简单地执行the typical state control(有关示例,请参阅“绑定到窗体和控件状态”部分).

请注意,在这种情况下,您还可以更简单地使用input[number]及其min参数.

在评论讨论后编辑:

好吧,NgModelController.$解析器中的函数显然只在模型内容发生变化时才被调用.你想要做的是在int1或int2改变时进行验证.所以就这样做:-):

link: function(scope,ctrl) {
    scope.$watch('data',function (data) {
      if (data.int2 > data.int1) {
          ctrl.$setValidity('higher',true);
          return data.int2;
      } else {
          ctrl.$setValidity('higher',false);
          return undefined;
    }
  },true);

使用你自己的验证变量(你的小提琴中的int2valid)也很奇怪.请使用the typical state control,类似于form.int2.$error.higher.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读