如何在angularjs指令添加验证属性 [英] How to add validation attributes in an angularjs directive

查看:183
本文介绍了如何在angularjs指令添加验证属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个角度指令,增加了验证属性标签,但它似乎并不奏效。这里是我的演示。你会发现,是有效的,如果你删除第二个输入框中的文本仍然是真实的,但去假的,如果你删除在第一个输入框中的文本。

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.

<一个href=\"http://plnkr.co/edit/Rr81dGOd2Zvio1cLYW8D?p=$p$pview\">http://plnkr.co/edit/Rr81dGOd2Zvio1cLYW8D?p=$p$pview

下面是我的指令:

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.

推荐答案

正在读取形式的编译阶段表​​单验证的所有规则,所以在子节点进行更改后,您需要重新编译格式指令(格式它在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:<一href=\"http://plnkr.co/edit/AB6extu46W4gFIHk0hIl?p=$p$pview\">http://plnkr.co/edit/AB6extu46W4gFIHk0hIl?p=$p$pview

这篇关于如何在angularjs指令添加验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆