【问题标题】:How to add validation attributes in an angularjs directive如何在 angularjs 指令中添加验证属性
【发布时间】:2013-09-26 11:21:40
【问题描述】:

我正在尝试编写一个向标签添加验证属性的角度指令,但它似乎不起作用。这是我的演示。您会注意到,如果您删除第二个输入框中的文本,“Is Valid”仍然为 true,但如果您删除第一个输入框中的文本,则“Is Valid”为 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);
        }
    };
});

我猜我只是缺少一些简单的东西。

【问题讨论】:

    标签: forms validation angularjs directive


    【解决方案1】:

    小心无限循环和重新编译,更好的解决方案在这里:Add directives from directive in 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);
              }
            };
          }
        };
      });
    

    工作插件可在:http://plnkr.co/edit/Q13bUt?p=preview

    【讨论】:

    • 非常感谢@Zymotik。请注意,replace 是不必要的,因为默认值为 false,并且至少从 v1.2.26 开始,replace 为 deprecated
    【解决方案2】:

    我知道这是一个相当古老的问题,但对于它的价值,角度文档描述了 ng-required,它采用布尔值。这解决了我遇到的类似问题。

    http://docs.angularjs.org/api/ng/directive/input

    【讨论】:

    • 这个答案是如何具体解决动态所需属性问题,而ng-required是针对该具体问题的最佳解决方案。另请参阅链接答案stackoverflow.com/a/23748401/404699
    【解决方案3】:

    所有的表单验证规则都在表单的编译阶段被读取,因此在子节点中进行更改后,您需要重新编译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);
              }
            }
        };
    });
    

    工作人员:http://plnkr.co/edit/AB6extu46W4gFIHk0hIl?p=preview

    【讨论】:

    • 我知道这很简单。话虽如此,它对我的​​价值并没有降低:)
    • 这对我不起作用。 @Zymotik 下面的解决方案确实有效。
    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    相关资源
    最近更新 更多