What is the best way to incorporate data from JSON objects in nested arrays within an array into HTML using AngularJS?

I have been struggling to display the JSON data in list.html in the desired format. Despite trying different approaches from similar posts, I have not been successful as my JSON structure is unique. How can I ensure that fields such as givenName, familyName, primaryTitle, phones[0].value, and photo.small are correctly displayed?

index.html:

<!doctype html>
<html lang="en" ng-app="directoryApp">
<head>
  <meta charset="UTF-8>
  <title>Directory</title>
  <script src="lib/angular/angular.min.js"></script>
  <script src="lib/angular/angular-route.min.js"></script>
  <script src="lib/angular/angular-animate.min.js"></script>

  <script src="js/app.js"></script>
  <script src="js/controllers.js"></script>
  <link rel="stylesheet" href="css/style.css">
</head>
<body>
<div ng-view></div>
</body>
</html>

list.html:

<ul ng-show="query">
    <li ng-animate="'animate'" ng-repeat="person in people.people | filter: query | orderBy: peopleOrder:direction">
        <img ng-src="images/{{person.photo.small}}" alt="Photo of {{person.name.givenName}}">
        <div class="info">
          <h2>{{person.name.givenName}}</h2>
          <h3>{{person.primaryTitle}}, {{person.phones[0].value}}</h3>
        </div>
    </li>
  </ul>

controllers.js:

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

directoryControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
  $http.get('js/directoryData.json').success(function(data) {
    $scope.people = data;
    $scope.peopleOrder = 'familyName';
  });
}]);

app.js:

var directoryApp = angular.module('directoryApp', [
  'ngRoute',
  'directoryControllers'
]);

directoryApp.config(['$routeProvider', function($routeProvider) {
  $routeProvider.
  when('/list', {
    templateUrl: 'partials/list.html',
    controller: 'ListController'
  }).
  otherwise({
    redirectTo: '/list'
  });
}]);

directoryData.json:

[
    {
        "uid": 15, 
        "name": "School of Programming", 
        "sortKey": 0, 
        "type": "Academic", 
        "address": {
            "address1": "255 Foo St",
            "address2": "Suite 310",
            "city": "FooBar",
            "state": "FB",
            "postalCode": "90210"
        },
        "phones": [
            {
                "type": "Work", 
                "value": "555-1616"
            },

            {
                "type": "Fax", 
                "value": "555-3620"
            }
        ],
        "people": [
            {
                "uid": "person1", 
                "classification": "Faculty", 
                "name": {
                    "givenName": "Roo",
                    "nickname": "",
                    "additionalName": "",
                    "familyName": "Baf"
                },
                "primaryTitle": "Part Time Worker",
                "phones": [
                    {
                        "type": "Work", 
                        "value": "555-1616"
                    },

                    {
                        "type": "Mobile", 
                        "value": "555-1509"
                    }
                ],
                "photo": {
                    "small": "/__media__/photos/foo_portrait_small.jpg", 
                    "medium": "/__media__/photos/foo_portrait_medium.jpg", 
                    "large": "/__media__/photos/foo_portrait_large.jpg"
                }
            },

            {
                "uid": "person2", 
                "classification": "Faculty", 
                "name": {
                    "givenName": "Foo",
                    "nickname": "",
                    "additionalName": "P.",
                    "familyName": "Bar"
                },
                "primaryTitle": "Blah",
                "phones": [
                    {
                        "type": "Work", 
                        "value": "555-3608"
                    },

                    {
                        "type": "Home", 
                        "value": "555-4716"
                    }
                ],
                "photo": {
                    "small": "/__media__/photos/portrait_small.jpg", 
                    "medium": "/__media__/photos/portrait_medium.jpg", 
                    "large": "/__media__/photos/portrait_large.jpg" 
                }
            }
        ]
    },
    {
        "uid": 16, 
        "name": "School of Coding", 
        "sortKey": 1, 
        "type": "Academic", 
        "address": {
            "address1": "256 Foo St",
            "address2": "Suite 311",
            "city": "FooBar",
            "state": "FB",
            "postalCode": "90210"
        },
        "phones": [
            {
                "type": "Work", 
                "value": "555-1616"
            },

            {
                "type": "Fax", 
                "value": "555-3620"
            }
        ],
        "people": [
            {
                "uid": "person3", 
                "classification": "Faculty", 
                "name": {
                    "givenName": "Boo",
                    "nickname": "",
                    "additionalName": "",
                    "familyName": "Far"
                },
                "primaryTitle": "Part Time Worker",
                "phones": [
                    {
                        "type": "Work", 
                        "value": "555-1617"
                    },

                    {
                        "type": "Mobile", 
                        "value": "555-1508"
                    }
                ],
                "photo": {
                    "small": "/__media__/photos/fooz_portrait_small.jpg", 
                    "medium": "/__media__/photos/fooz_portrait_medium.jpg", 
                    "large": "/__media__/photos/fooz_portrait_large.jpg"
                }
            },

            {
                "uid": "person4", 
                "classification": "Faculty", 
                "name": {
                    "givenName": "Too",
                    "nickname": "",
                    "additionalName": "P.",
                    "familyName": "Mar"
                },
                "primaryTitle": "Blah",
                "phones": [
                    {
                        "type": "Work", 
                        "value": "555-3607"
                    },

                    {
                        "type": "Home", 
                        "value": "555-4717"
                    }
                ],
                "photo": {
                    "small": "/__media__/photos/Xportrait_small.jpg", 
                    "medium": "/__media__/photos/Xportrait_medium.jpg", 
                    "large": "/__media__/photos/Xportrait_large.jpg" 
                }
            }
        ]
    }
]

Answer №1

In your data structure, there are arrays of objects with a property called people containing an array of values.

To iterate through this structure, you'll need to utilize nested ng-repeat. The first loop will cycle through the main array, while within each iteration of this loop, you'll loop through the inner array.

<ul ng-repeat="group in data"> 
   <li ng-animate="'animate'" ng-repeat="person in group.people | filter: ...">

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

Issue with Jquery similar to javascript createElement

I am attempting to replicate the code below using jQuery: var newElem = document.createElement("div"); newElem.innerHTML = "DynaColumn"; newElem.className = "ui-state-default ui-corner-all"; return newElem; This is the jQ ...

Pick and modify a particular component in ReactJS

Currently, I am working on a project in ReactJS where I am attempting to toggle the colors of two buttons. While I have successfully set the active state property of the selected button, I am facing challenges with changing the style of another button (cal ...

Using Object Values and Subvalues to Assign Element Attributes in jQuery

I have a weekly schedule that I update regularly using a static table layout: <table> <tr class="live gm fsp"> <td>Oct. 7</td> <td>12:30 pm</td> <td class="prog">Show 1</td> <td>Team ...

Error: Uncaught TypeError - Unable to access the 'handleClick' property of undefined within a forEach loop

I came across the following code snippet articles_list.jsx import React from 'react'; import './articles_list.css'; export default class ArticlesList extends React.Component { constructor(props) { super(props); this.state ...

Steps to automatically launch a URL upon button click and executing PHP script

I have a Joomla website and I am facing a challenge in automatically triggering a modal window that displays a web page based on parameters passed through the URL. The scenario on my website is as follows: A trip leader selects a trip and schedules it by ...

Craft a brief description for every individual component discovered

Is there a way to identify and shorten all elements containing a <tspan> tag to just ten characters each? For example: <tspan>Bla bla bla bla</tspan> <tspan>Bla bla bla bla</tspan> <tspan>Bla bla bla bla</tspan> ...

Transforming HTML tables into JSON using JQuery

My table contains rows with specific classes, and I need to convert it into JSON for server-side usage. Below is the content of the table: <table class="tableContent"> <thead> <tr class="header"> <th class="col1">RoleNa ...

Exploring ways to display featured posts within specific category sections

I have 2 featured posts in 1 div id, one with a big class and the other with a small class. I want the big featured div to display posts based on categories. The code for the big featured post is shown below: <div class="main_feat"> ...

Enhance your message inbox experience with jQuery/Javascript features inspired by Gmail, including the ability to select all messages with a checkbox and

It is truly satisfying to be here working on developing a private message inbox for my website, especially after successfully implementing a complete user signup/login and activation system. A few months ago, I never believed I had enough patience to grasp ...

How can I change a Task into a List in this scenario?

Help needed with this issue... Encountering an error message: Unable to convert type 'System.Threading.Tasks.Task System.Collections.Generic.List Thoughts.ViewModel.PickerViewModel.Location'** to **'System.Collections.Generic.List Thought ...

Align the headers of columns to the right in the AgGrid widget

Is there a way to align the column headers to the right in AgGrid without having to implement a custom header component? It seems like a lot of work for something that should be simple. You can see an example here: https://stackblitz.com/edit/angular-ag-g ...

The function buf.writeBigUInt64BE is not recognized as a valid function and returns an undefined error

I'm attempting to implement the code below on my React Native iOS device: import { Buffer } from "buffer"; const buf = Buffer.alloc(8) buf.writeBigUInt64BE(BigInt(123), 0) const value = buf.readBigUInt64BE(0) console.log(value) However, I&a ...

Sending database data from PHP to JavaScript - mysql_fetch_array behaving unexpectedly

Forgive me if there is already an answer out there to my question, but after a week of searching online and experimenting, I decided to turn to the experts for help. Purpose: My goal is to query an SQL database using server-side code (specifically PHP), t ...

Creating nodes using JSON selector is a straightforward process that involves identifying the specific

I have JSON data containing information about various papers and their publication venues, presented in the following format: {"id": "1", "title": "Paper1", "venue": {"raw": "Journal of Cell Biology"}} {"id": "2", "title": "Paper2", "venue": {"raw": "Natu ...

Utilizing Jest to Mock a jQuery Method within a Promise

I have created a function that utilizes a jQuery function named dataFunc, which is expected to return an object. Instead of testing the dataFunc function itself, I want to focus on testing the promise it produces. To achieve this, I need to mock the respo ...

How can you use jQuery to display an image when hovering over text?

Looking for a tutorial or script that displays an image when hovering over HTML text with the mouse? ...

Display additional content button, dynamic div identification

I've created a small script that includes a "show more" button at the end of displaying 10 entries. Here is the code: <div id="more<?=$lastid;?>"> <a onclick="showmore(<?=$lastid;?>);">More</a> </div> And here ...

Strategies to verify if two objects of the same class possess the same attribute

I have multiple elements with the same class and unique attribute values, such as: <div class="myclass" data-attr="1"></div> <div class="myclass" data-attr="2"></div> <div class="myclass" data-attr="3"></div> <div cl ...

Modify the variable when a model undergoes alterations

How can I update a variable in my controller when one of the input models changes? I have two separate models for each input field, and I want to merge them into a new variable. However, this new variable does not update automatically when the input models ...

Modifying browser.location.href Cancels AJAX Requests

I am facing an issue with my HTML page. I have a button that, when clicked by the user, updates the window.location.href to the URL of a text file. In order to ensure that the file is downloaded and not opened in the browser, the text file is served with C ...