Les*_*nks 12 forms validation directive angularjs
我正在尝试编写一个角度指令,为标签添加验证属性,但它似乎没有工作.这是我的演示.您将注意到,如果删除第二个输入框中的文本,"Is Valid"仍然为true,但如果删除第一个输入框中的文本则为false.
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);
}
};
});
Run Code Online (Sandbox Code Playgroud)
我猜我只是缺少一些简单的东西.
OZ_*_*OZ_ 20
表单验证的所有规则都在表单的编译阶段读取,因此在子节点中进行更改后,需要重新编译form
指令(form
它是AngularJS中的自定义指令).但只做一次,避免无限循环(你的指令的'链接'函数将在表单编译后再次调用).
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);
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
工作人员:http://plnkr.co/edit/AB6extu46W4gFIHk0hIl?p =preview
Zym*_*tik 10
注意无限循环和重新编译,这里有一个更好的解决方案:在AngularJS中添加指令
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
terminal: true, //this setting is important to stop loop
priority: 1000, //this setting is important to make sure it executes before other directives
compile: function compile(element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
}
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
工作插件可在以下网址获得:http://plnkr.co/edit/Q13bUt?p = preview