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

设置AngularJS指令的多个输入的有效性

发布时间:2020-12-17 10:20:44 所属栏目:安全 来源:网络整理
导读:我正在尝试创建一个指令,当一个控件的值发生更改时,该指令可用于重置组中多个输入控件的验证状态.组由 HTML中指令集的属性标识. 例如: – 当用户更改其中一个控件输入值时,From Date和To Date输入都会重置有效性状态 这就是我到目前为止所拥有的 JS /角 ang
我正在尝试创建一个指令,当一个控件的值发生更改时,该指令可用于重置组中多个输入控件的验证状态.组由 HTML中指令集的属性标识.
例如: – 当用户更改其中一个控件输入值时,From Date和To Date输入都会重置有效性状态

这就是我到目前为止所拥有的

JS /角

angular.module('myModule').directive('groupedInputs',function () {
    return {
        restrict: 'A',require: '?ngModel',link: function (scope,element,attrs,ctrl) {
            element.on('change',function () {

                // Resetting own validity
                scope.$apply(ctrl.$setValidity('server',true));

                // Here I need to set the validity of the controls which
                // have the `GroupedInputs` directive with the 
                // same  attribute value
            });
        }
    };
});

HTML

<input name="FromDate" type="date" class="form-control" ng-model="model.FromDate" grouped-inputs="FromToDates">
<input name="ToDate" type="date" class="form-control" ng-model="model.ToDate" grouped-inputs="FromToDates">

它可以重置自己的输入控件的有效性,但不能使用指令和相同的属性值访问其他输入控件.通过查询具有相同属性的输入,访问其他控件的最佳角度方式是什么?

我会尝试通过实现帮助对象来存储组元素控制器以及添加到组中的方法以及组中所有元素的setValidity来解决此问题.

像这样的东西:

angular.module('myModule').directive('groupedInputs',function() {

    var groupControls = {
        groups: {},add: function(name,ctrl) {
            this.groups[name] = this.groups[name] || [];
            this.groups[name].push(ctrl);
        },setValidity: function(name,key,value) {
            this.groups[name].forEach(function(ctrl) {
                ctrl.$setValidity(key,value);
            });
        }
    };

    return {
        restrict: 'A',link: function(scope,ctrl) {

            // Add element controller to the group
            groupControls.add(attrs.groupedInputs,ctrl);

            element.on('change',function() {

                // When needed,set validity of elements in the group
                groupControls.setValidity(attrs.groupedInputs,'server',false);
                scope.$apply();

            });
        }
    };
});

演示:http://plnkr.co/edit/fusaaN6k9J5SZ7iQA97V?p=preview

(编辑:李大同)

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

    推荐文章
      热点阅读