如何在 angularjs 指令中添加验证属性 [英] How to add validation attributes in an angularjs directive
问题描述
我正在尝试编写一个向标签添加验证属性的 angular 指令,但它似乎不起作用.这是我的演示.您会注意到,如果您删除第二个输入框中的文本,Is Valid"仍然为真,但如果您删除第一个输入框中的文本,则为假.
I am trying to write an angular directive that adds validation attributes to the tag, but it doesn't seem to be working. Here is my demo. You will notice that "Is Valid" remains true if you delete the text in the second input box, but goes to false if you delete the text in the first input box.
http://plnkr.co/edit/Rr81dGOd2Zvio1cLYW8D?p=preview
这是我的指令:
angular.module('demo', [])
.directive('metaValidate', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.attr("required", true);
}
};
});
我想我只是缺少一些简单的东西.
I'm guessing I am just missing something simple.
推荐答案
表单的所有验证规则都是在表单的编译阶段读取的,所以在子节点中进行更改后,需要重新编译form
指令(form
它是 AngularJS 中的自定义指令).但只做一次,避免无限循环(你的指令的链接"函数将在表单编译后再次调用).
All rules for validation of the form are being read in compilation phase of the form, so after making changes in a child node, you need to recompile form
directive (form
it's a custom directive in AngularJS). But do it only once, avoid infinite loops (your directive's 'link' function will be called again after form's compilation).
angular.module('demo', [])
.directive('metaValidate', function ($compile) {
return {
restrict: 'A',
link: function (scope,element, attrs) {
if (!element.attr('required')){
element.attr("required", true);
$compile(element[0].form)(scope);
}
}
};
});
工作plunker:http://plnkr.co/edit/AB6extu46W4gFIHk0hIl?p=preview
这篇关于如何在 angularjs 指令中添加验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!