动态ng消息和验证

时间:2015-07-23 08:25:29

标签: javascript json angularjs

我已经以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"
        }
    },

我使用compile函数通过custom指令将规则包含到input元素中。现在规则被设置为输入字段,表单验证正在运行。

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

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

如何将错误放在页面上?

1 个答案:

答案 0 :(得分:0)

我找到了一种方法来打印从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。

相关问题