【问题标题】:Dynamic ng-messages and validation动态 ng 消息和验证
【发布时间】:2015-07-23 08:25:29
【问题描述】:

我已经设置了json格式的验证规则,它存储在工厂服务中。

    "inputname":{
        "rule":{
            "required":"required", "ng-minlength":"3", "ng-maxlength":"16"
        },
        "error":{
            "required":"Name is required",
            "minlength":"Name must have atleast 3 characters",
            "maxlength":"Name can have upto 16 characters"
        }
    },

我使用编译功能通过自定义指令将规则包含到输入元素中。现在规则已设置到输入字段并且表单验证正在工作。

我需要在 html 的不同部分显示错误。

我需要通过从服务中收集 json 中的错误来在 html 中打印 <ng-messages>

如何将错误放在页面上?

【问题讨论】:

    标签: javascript json angularjs


    【解决方案1】:

    我找到了一种打印从 json 文件中获取的错误消息的方法。就像我说的那样,我的输入指令在验证方面工作得很好。这个答案是如何打印错误信息。

    此代码是为我的目的而编写的。所以在这里我在我的 html 中声明了另一个指令,只是为了显示错误。我找到了这种方式,它可能不是最好的。如果有更好的建议。

    gb_dash.directive('formErrors', ['$compile', 'formRules', function($compile, formRules){
    return{
        restrict: 'A',
        replace: false, 
        compile: function compile(element, attrs) {
    
            element.removeAttr("form-errors"); //remove the attribute to avoid indefinite loop
            element.removeAttr("set-type");
            element.removeAttr("form-name");
    
    
            formName = attrs.formName;
            rules = formRules.getAllRules(attrs.setType);
            console.log(rules);
            str ='';
    
            $.each(rules, function(inputName, value){
                str += '<ng-messages for="'+formName+'.'+inputName+'.$error" ng-if="'+formName+'.'+inputName+'.$touched || '+formName+'.'+inputName+'.$dirty">';
    
                    $.each(value.error, function(key, value){
                        //console.log(key, value);
                        str+='<ng-message msg-bubble when="'+key+'">'+'<span class="label alert">'+value+'</span>'+'</ng-message>'
                    });
                str += '</ng-messages>';
            });
    
            element.html(str);
    
        }
    }
    
    }]);
    

    这里的 formRules 是我的工厂,包含规则和错误 json。

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      相关资源
      最近更新 更多