Angularjs 如何有条件地将自定义验证器应用于表单字段?
我有一个可重用的指令,其中自定义验证器的使用是可选的 有条件地应用此验证器属性的好方法是什么Angularjs 如何有条件地将自定义验证器应用于表单字段?,angularjs,validation,angular-directive,Angularjs,Validation,Angular Directive,我有一个可重用的指令,其中自定义验证器的使用是可选的 有条件地应用此验证器属性的好方法是什么 <input type="text" name="{{name}}" require-items="{{requireitems}}" mongoose-error> 在my指令指令链接功能中: link: function(scope, iElement, iAttrs, controller) { if(iAttrs.requ
<input type="text"
name="{{name}}"
require-items="{{requireitems}}"
mongoose-error>
在
my指令
指令链接
功能中:
link: function(scope, iElement, iAttrs, controller) {
if(iAttrs.requireItems) {
// checks if require-items is present
// process your validation here
}
}
检查在
ng required
中是如何完成的,使用属性并观察相同的属性来处理动态更改
var requiredDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
ctrl.$validators.required = function(modelValue, viewValue) {
return !attr.required || !ctrl.$isEmpty(viewValue);
};
attr.$observe('required', function() {
ctrl.$validate();
});
}
};
};
共享您的指令代码
var requiredDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
ctrl.$validators.required = function(modelValue, viewValue) {
return !attr.required || !ctrl.$isEmpty(viewValue);
};
attr.$observe('required', function() {
ctrl.$validate();
});
}
};
};