gpt4 book ai didi

angularjs - 设置来自 AngularJS 指令的多个输入的有效性

转载 作者:行者123 更新时间:2023-12-02 11:26:59 25 4
gpt4 key购买 nike

我正在尝试创建一个指令,当其中一个控件的值发生更改时,该指令可用于重置组中多个输入控件的验证状态。组由 HTML 中设置的指令的属性来标识。例如: - 当用户更改其中一个控件输入值时,起始日期截止日期输入都会重置有效性状态

这就是我目前所拥有的

JS/Angular

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">

可以重置自身输入控件的有效性,但不能访问具有指令和相同属性值的其他输入控件。通过查询具有相同属性的输入来访问其他控件的最佳 Angular 方式是什么?

最佳答案

我会尝试通过实现辅助对象来存储组元素 Controller 来解决此问题,并提供添加到组中的方法以及组中所有元素的 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',
require: '?ngModel',
link: function(scope, element, attrs, 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

关于angularjs - 设置来自 AngularJS 指令的多个输入的有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30409910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com