我可以以编程自定义指令内部应用角度验证的指令? [英] Can I programmatically apply Angular validation directives inside a custom directive?
问题描述
我已经找到了HTML输入如下形式的大量出现,这是电话号码:
I have found great many occurrences of the following pattern for html inputs, this being for phone numbers:
<input type="text" ng-model="CellPhoneNumber" required ng-pattern="/^[0-9]+$/" ng-minlength="10" />
我想创建一个自定义指令,随时随地应用,会告诉角度运用这三个规则,例如:
I would like to create a custom directive that, wherever applied, will tell Angular to apply all three of these rules, e.g:
<input type="text" ng-model="CellPhoneNumber" bk-ng-validation="phoneNumber"/>
然后,code在我的指令,会发现并调用调用的函数 phoneNumber的
,其中我想看到类似这样的:
Then, code in my directive would find and invoke a function called phoneNumber
, in which I would like to see something like:
清单1:
function bkNgPhoneNumber(model) {
// This is purely SPECULATIVE pseudo-code, just to convey an idea.
model.errors.add(applyMinLength(10, model));
model.errors.add(applyMaxLength(15, model));
model.errors.add(applyPattern("/^[0-9]+$/", model));
}
我想preFER上面的方法在改写code对于这些规则,例如:
I would prefer the above approach over 'rewriting code for these rules, e.g:
清单2:
function phoneNumber(model) {
if (model.length < 10 || model.length > 15) {
model.errors.add("Must be 10 to 15 chars!");
}
}
我不希望废除所有基于属性的指令,但preferably创建一个宏观指令,将调用我的清单1 code,这将调用实习生一套更微验证。
I don't want to do away with all attribute based directives, but preferably create a 'macro' directive that will invoke my Listing 1 code, which will intern invoke a set of more 'micro' validations.
推荐答案
要做到这一点(即应用现有的验证无C再次写自己的$ C $)将添加验证指示各自的属性和强制重新单程-compile。这需要你的指令有一个足够高的优先级,而且是端子:真正的
One way to do this (i.e. apply existing validators without writing their code again) would be to add the validation directives' respective attributes and force a re-compile. This would require your directive to have a high-enough priority and also be terminal: true
.
app.directive("bkNgValidation", function($compile){
return {
priority: 10000,
terminal: true,
link: function(scope, element){
element.attr("ng-required", "true");
element.attr("ng-minlength", 20);
element.attr("ng-maxlength", 30);
// prevent infinite loop
element.removeAttr("bk-ng-validation");
$compile(element)(scope);
}
};
});
Demo
这篇关于我可以以编程自定义指令内部应用角度验证的指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!