Dynamic ng messages and validation

I have set up validation rules in json format and stored in a factory service.

    "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"
        }
    },

      

I have included the rules in the input element by a special directive using a compile function. Now the rules are being set in the input field and the form validation is working.

I need to display errors in another part of the html.

I needed to print <ng-messages>

to html while collecting erros to json from a service.

How do I post errors on the page?

+3


source to share


1 answer


I found a way to print out error messages extracted from json file. As I said, my input directives work with validation. This answer is for how to print error messages.

This code is executed for my purpose. So here I have declared another directive in my html just to show errors. I found this way and it may not be the best. If there is a more kind suggestion.



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);

    }
}

}]);

      

here formRules is my factory containing json rules and errors.

0


source







All Articles