Interactive ng-messages and validation

Validation rules have been set in JSON format and are stored within a factory service.

    "inputname":{
        "rule":{
            "required":"required", "ng-minlength":"3", "ng-maxlength":"16"
        },
        "error":{
            "required":"Name is required",
            "minlength":"Name must have at least 3 characters",
            "maxlength":"Name can have up to 16 characters"
        }
    },

The rules have been added to the input element using a custom directive with a compile function. As a result, form validation is now functioning correctly.

The goal now is to display any errors in a different section of the HTML.

To accomplish this, I would like to include <ng-messages> in the HTML by retrieving error messages from a service in JSON format.

What steps should be taken to properly showcase these errors on the page?

Answer №1

I have successfully implemented a method to display error messages retrieved from a JSON file. Despite my input directives functioning properly for validation, this particular Answer focuses on the process of printing out error messages.

This code was specifically created for my own requirements. As a result, I introduced an additional directive in my HTML to specifically handle errors. While this solution works for me, I am open to suggestions for improvement if there is a more efficient approach available.

gb_dash.directive('formErrors', ['$compile', 'formRules', function($compile, formRules){
return{
    restrict: 'A',
    replace: false, 
    compile: function compile(element, attrs) {

        element.removeAttr("form-errors"); //prevent infinite 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);

    }
}

}]);

In this scenario, the factory formRules stores the rules and error information in JSON format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error with Jquery authentication

Take a look at the code snippet below: var jsonData1 = $.ajax({ url: 'http://'+domainName+':9898/jolokia/read/*', dataType:"json", crossDomain: true, beforeSend: function(xhr){ var username= '*&a ...

Leverage identical functions across various arrays within an Angular directive

Seeking help with AngularJS as a beginner, I'm struggling to reuse functions across different arrays. There is just one array with 2 more arrays within it. Can someone point out my mistake, please? Thank you. <body ng-controller="MainCtrl as main ...

A guide on resolving the 'Unexpected identifier array in JSON Parse Error' encountered during an AJAX Request

I'm currently working on setting up a Contact Form Validation and I require the variable $msg from a php script called 'sendEmail.php'. The actual mailing system is functional, as the script successfully receives form inputs from index.php a ...

What would be your suggestion for transferring data in text format between multiple programs?

Our software program must handle the import and export of data to and from various applications, each with its own unique properties. Many of these companies will send us two text files: one containing the actual data and another with descriptions. For ex ...

Steps for displaying a website within a specific Div using HTML

I'm trying to set up a website to open within a specific <div> tag, like the example shown in this link: Responsive. Can anyone spot what I'm doing incorrectly? <html> <head> <script> function mobile320() { ...

Is the Javascript framework malfunctioning even though the code is identical to the one on jsfiddle

<html> <head> <meta charset="UTF-8"> <title>Interactive Globe Display using iTowns</title> <style> html { height: 100%; } body { margin: 0; overflow: hidden; ...

Selecting an option from the dropdown menu to automatically fill in a textbox within

I've run into a small hiccup with some javascripts/AJAX and could really use some guidance in the right direction. My issue involves populating the per-carton-price-field using collection_select within a form. This form is meant to generate an entry ...

Utilizing Symfony REST DTO validation and injecting it into the Model similar to a paramconverter

Is there a way to create a request filter for post actions in a JSON REST API that takes the request's body, fills the DTO, validates it, and injects it into the controller action like paramconverter? I have an ExampleDTO structured like this: class ...

Incorporating jQuery into Rails 6.1

I encountered some difficulties while setting up jQuery in rails 6.1, even though I believe it's configured correctly. Below are the steps I've taken: Installed yarn add jquery 2. In config/webpack/environments.js, I made the following changes ...

Is there a way to incorporate text at the end of a row in HTML?

I have a photo and some text on my website. The photo is displayed on the left side, while the text appears nicely on the right side. Now, I am looking to include an additional block of text below the existing text. How can I accomplish this? What steps ...

Inform jQuery that the draggable element is in the process of being dragged dynamically

Currently, this issue is a vital component of an ongoing task. Once we can resolve this issue, it will lead to the completion of this and another inquiry. The original objective can be found here: drag marker outside map to html element You can view the ...

My Angular JS http.get request is failing to reach the specified URL

While working with AngularJS to integrate RESTful web services into my website, I am encountering an issue where I am consistently receiving errors instead of successful responses. I have been stuck on this for the past three days and any assistance would ...

sorting through entries in a dictionary

I have a query about using inverse filtering in dictionaries. Here's an example dictionary: dico = { Pierre:{ 'Math':16, 'Chimie':09, 'Dessin':18, 'Electronic':20, ...

Divide a column containing dictionaries into individual columns using pandas

I have data stored in a postgreSQL database. Using Python2.7, I am retrieving this data and converting it into a Pandas DataFrame. However, the last column of this dataframe contains dictionaries of values. The DataFrame df is structured as follows: Statio ...

Execute the extension exclusively within iframes

I'm developing a browser extension and I need certain parts of the code to only execute within iframes. Currently, all the code in my extension.js file is executed on both regular web pages and iframes. How can I identify whether the code is running w ...

Learn how to implement data-binding in AngularJS using the ui-router and ControllerAs syntax, all without the

I have been following the guidelines laid out by John Papa, but I am facing difficulty in binding values from child controllers to parent controllers using ui-router, ControllerAs, and vm variables instead of $scope. In my attempts, I created two example ...

What causes objects to intersect in A-Frame even when they are seemingly distanced from each other?

My charts appear in front of a globe object in A-Frame, but when I move the camera in the scene, the order of objects changes causing the charts to overlap and become invisible. I'm unsure of the cause and how to fix it. Here are some screenshots of t ...

Enable a click event within an iFrame by clicking on an element in the parent document

I am attempting to trigger the click event of an element inside an iFrame (specifically a standard Twitter follow button) when clicking on an element within my main webpage. Below is the code snippet I have been experimenting with, but unfortunately it do ...

Can you explain how to create a function in Angular that accepts a number as an argument and then returns the square of that number?

I am working with an array of numbers and I want to show each number in the list along with its square value. To do this, I need to create a function that takes a number as input and returns its square as output. Here is what I have attempted so far: co ...

Guide to utilizing sections within Angular

Planning to develop a website using Asp.net WebAPI and AngularJs. Seeking advice on how to separate the admin area from the user interface of the site. In my previous project, I utilized the MVC area to create an admin section. A friend recommended crea ...