Dynamic array of objects in Angular using ng-repeat

When given a JSON array of objects, how can one dynamically display it using ng-repeat? The key error is static and always remains the same. Only the values of error change. For example, if the password field has an error, then the key will be password in place of error.

{ 
  "error":  {
    "firstName": {
      "0": "The first name field is required.",
      "1": "The first name field must have 2-5 characters."
    },
    "lastName": {
      "0": "The last name field is required."
    }
  }
}

.

{ 
  "error":  {
    "password": {
      "0": "The password field is required."
    }
  }
}

I attempted to do this:

<ul ng-repeat="message in errormessage">
    <li ng-repeat="(k,v) in message">
         {{k}} - {{v}}
    </li>
</ul>

However, instead of the desired output, it displays:

0 - [
0 - ]

Answer №1

angular.module('app', [])
  .controller('SampleCtrl', function($scope) {
    $scope.errormessages = {
      "error": {
        "firstName": {
          "0": "The first name field is required.",
          "1": "The first name field must have 2-5 characters."
        },
        "lastName": {
          "0": "The last name field is required."
        },
        "password": {
          "0": "The password field is required."
        }
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="SampleCtrl">

  <ul ng-repeat="message in errormessages">
    <li ng-repeat="(k,v) in message">
      <b>{{k}}:</b><br>
      <ul>
        <li ng-repeat="err in v">
          {{err}}
        </li>
      </ul>
    </li>
  </ul>
</div>

Answer №2

Double check that you are utilizing the ng-repeat on the correct object. Your current setup looks like this:

ng-repeat="message in errormessage"

However, it appears that the content of errormessage is actually "[]". Take a look at this example for reference.

Answer №3

Here are some key points:

  • If you have a JSON object that contains an array of objects
    , make sure your JSON is structured correctly.
  • Instead of using
    ng-repeat="message in errormessage"
    , try using
    ng-repeat="message in errormessage.error"
    .

Check out this DEMO:

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    $scope.errormessage = { 
  "error":  {
    "firstName": {
      "0": "The first name field is required.",
      "1": "The first name field must have 2-5 characters."
    },
    "lastName": {
      "0": "The last name field is required."
    }
  }
}

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
 <ul ng-repeat="message in errormessage.error">
    <li ng-repeat="(k,v) in message">
         {{k}} - {{v}}
    </li>
</ul>
</div>

Answer №4

UPDATE

In my opinion, the initial step to take into account is normalizing your JSON data if you have the ability to do so, and representing it in the following structure:

$scope.errors = {
  "error": {
        "firstName": {
            "0": "The first name field is required.",
            "1": "The first name field must have 2-5 characters."
        },
        "lastName": {
            "0": "The last name field is required."
        },
        "password": {
             "0": "The password field is required."
        },
        "email": {
            "0": "The email field is required.",
            "1": "The email field must have 2-5 characters."
        },
        "newsletter": {
             "0": "The newsletter field is required."
        },
        "address": {
             "0": "The address field is required."
        }
    }
}

This approach is recommended because having two fields named error within the same object or array can create conflicts. Once this normalization is done, the provided solution should function as intended.

<div ng-app="app" ng-controller="SampleCtrl">
    <ul ng-repeat="message in errors">
       <li ng-repeat="(k,v) in message">
         <b>{{k}}:</b><br>
         <ul>
            <li ng-repeat="err in v">
             {{err}}
            </li>
         </ul>
       </li>
    </ul>
</div>

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

A guide on extracting data from a mongoose model and assigning it to a variable in a manner similar to the MVC design pattern

Below is an example of MVC framework code in PHP. I'm seeking advice on how to implement a similar process in Node.js using Mongoose. I am working with Node.js, MongoDB, and REST API development. Controller file: <?php class Myclass { public fu ...

Learn how to dynamically incorporate multiple Bootstrap collapse elements in PHP

I've encountered an issue with my code that contains both HTML and PHP. The problem arises when there are multiple elements in a collapse, as only the first element works properly. This is due to the fact that each element has the same id named "colla ...

Leveraging environmental variables in a Vue.js web application

The article I recently came across discussed how to effectively utilize environment variables in vuejs. Following the instructions, I set up my local .env.local file and also installed dotenv. VUE_APP_AUTH_AUTHORITY = 'http://localhost/auth' I ...

Continuously incorporating Ajax requests into a queue

I'm currently tackling a new feature at work and find myself at a crucial point. Despite being unfamiliar with Ajax, I am determined to set up a manual queue to handle the requests instead of relying on the browser. After some research and referring t ...

Having difficulty executing a function inside a JavaScript file

Within my index.php file, the following lines of code are present: <!doctype html><html class=""><head><title>a title</title> <link href="_css/boilerplate.css" rel="stylesheet" type="text/css"> <script type="text/jav ...

Inquiring about the status of uploads in the AjaxFileUpload to ensure files have been successfully uploaded

How can I check if the file selected in AjaxFileUpload has already been uploaded or is pending? For example: https://i.stack.imgur.com/q6qUQ.png I want to validate files that are still pending upload. Here is my .aspx page code <form id="form1" runa ...

Is it possible for me to add images to the input file individually before submitting them all at once?

When images are inserted one by one, the 'input file' only reads one picture at a time. However, when images are inserted in multiple quantities, the result is displayed for each image that the user inputs. window.onload = function() { //Ch ...

Connect the scroll wheel and then proceed to scroll in the usual way

There are two div elements with a height and width of 100%. One has the CSS property top:0px, while the other has top 100%. I have implemented an animation that triggers when the mousewheel is used to scroll from one div to the other. The animation functi ...

Running a 2D JavaScript game script on a React page - A step-by-step guide!

I am facing a challenge with my website that features a game coded entirely in javascript. Despite my efforts to switch the site from an HTML layout to a more modern React design, I can't seem to get the game to display correctly. In the original HTM ...

Ways to retrieve information from a database using a specific ID stored in a JSON format

My device has generated a JSON file with an ID that needs to be deserialized. I want to use this ID as a parameter to select data from my database. Can anyone assist me with this? ...

Tips for effectively incorporating NSOperation Queue in objective c

I have encountered an issue with the code below. I am utilizing NSOperationQueue to fetch post data from the server during the login process. My aim is to retrieve a response from the server 8 times. However, the implementation of NSOperationQueue seems to ...

What is the best way to retrieve the previously chosen value from one dropdown and populate it into another dropdown when

I have 3 choices available. When the user selects the third option, a jQuery onchange event is triggered to send the variable to another PHP file for database validation based on the selected id. The challenge lies in how I can also include the variables f ...

Combine the power of JavaScript with Node.js

I am brand new to the world of node and feeling a bit lost when it comes to finding the right solution for my current issue. I would greatly appreciate any guidance towards the best approach. Currently, I am using the Buddy framework to compile coffeescri ...

Element not chosen in Angular version 6

Recently delving into Angular 6, I've been working on setting up form validation within an Angular form. Validation has been successfully implemented, but there's a minor issue with the select box displaying an empty first value. Here is my code ...

Mastering Vue 3: Simplifying a reactive array of objects while maintaining reactivity

Struggling with maintaining reactivity in Vue 3 when flattening a nested array of objects. Unfortunately, my attempts result in crashing and browser hang-ups. In my Vue 3 component, I have an array structured as a list of objects: this.grouped = [ ...

React Native: Avoiding Infinite Loops in useEffect

I am facing an issue where my app goes into an infinite loop because pointsData is inside the useEffect function. How can I resolve this situation? function useGetPoints() { const [pointsData, setPointsData] = useState<PointTbleType[]>([]); ...

Hide the HTML DIV without altering the position of the current div

My goal is to conceal elements 1, 3 and 2 & 4 without changing their position. div{ width: 10%; float: left; } <div style="background-color: blue"><p>1</p></div> <div style="background-color: yellow"><p>2</ ...

Axios encounters CORS issues, while fetch operates smoothly

After going through various questions on CORS errors to no avail, I am facing a dilemma in my NuxtJS client application. Whenever I try to make a simple POST request using axios, I encounter CORS issues. However, when I switch to using the fetch API, every ...

Ways to identify when all images have been loaded during a dynamic page load

I am trying to load a page with images into a div element. I need to find out when all the images on that dynamically added page have finished loading. $("#main").load('imagespage.php', function(){ alert("Page loaded"); }); The problem is that ...

The specified selector is invalid or illegal in HTMLUnit

Attempting to mimic a login using htmlunit has presented me with an issue despite following examples. The console messages I have gathered are as follows: runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' erro ...