Best Practices for Iterating over Nested Objects and Arrays Using ng-repeat

I've been trying to use Angular's ng-repeat, but nothing seems to work for me. I'm attempting to loop through companies.users and display all the first names. Any assistance would be greatly appreciated! Thank you!

<div ng-app="app" ng-controller="appCtrl">
<div ng-repeat="user in companies.users">
<p>{{user.firstName}}</p>
<div>
app.controller('appCtrl', function($scope){
    $scope.companies = [{
        name: 'The Best Company Denim',
        users: [{
            firstName: 'Alex',
            lastName: 'D',
            number: 1234
        }, {
            firstName: 'Sarah',
            lastName: 't',
            number: 14
        }, {
            firstName: 'J',
            lastName: 'd',
            number: 07
        }]
    }, {
        name: 'The Best Company Elegant',
        users: [{
            firstName: 'Alx',
            lastName: 'B',
            number: 1234
        }, {
            firstName: 'Seth',
            lastName: 'w',
            number: 12
        }, {
            firstName: 'J.S',
            lastName: 'B',
            number: 7
        }]
    }, {
        name: 'The Best Company by Julia',
        users: [{
            firstName: 'Aleddddx',
            lastName: 'l',
            number: 1234
        }, {
            firstName: 'Maggy',
            lastName: 'n',
            number: 1
        }, {
            firstName: 'Ja',
            lastName: 'Key',
            number: 123
        }]
    }]
});

Answer №1

If you want to display nested data in AngularJS, you can use a nested ng-repeat.

<div ng-repeat="company in companies">
  <div ng-repeat="user in company.users">
    <p>{{user.firstName}}</p>
  </div>
<div>

Here is an example:

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.companies = [{
      name: 'The Best Company Denim',
      users: [{
        firstName: 'Alex',
        lastName: 'D',
        number: 1234
      }, {
        firstName: 'Sarah',
        lastName: 't',
        number: 14
      }, {
        firstName: 'J',
        lastName: 'd',
        number: 07
      }]
    }, {
      name: 'The Best Company Elegant',
      users: [{
        firstName: 'Alx',
        lastName: 'B',
        number: 1234
      }, {
        firstName: 'Seth',
        lastName: 'w',
        number: 12
      }, {
        firstName: 'J.S',
        lastName: 'B',
        number: 7
      }]
    }, {
      name: 'The Best Company by Julia',
      users: [{
        firstName: 'Aleddddx',
        lastName: 'l',
        number: 1234
      }, {
        firstName: 'Maggy',
        lastName: 'n',
        number: 1
      }, {
        firstName: 'Ja',
        lastName: 'Key',
        number: 123
      }]
    }];
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <div ng-repeat="company in companies">
    <div ng-repeat="user in company.users">
      <p>{{user.firstName}}</p>
    </div>
  </div>
</div>

Answer №2

Do you prefer this format: https://codepen.io/sheriffderek/pen/944e812b0cd218f2a7990fad8bcafc5d/ ?

HTML Markup

<section ng-app="myApp" ng-controller="myCtrl">

    <ul class="company-list">
        <li class="company" ng-repeat="company in companies">
            {{company.name}}
            
            <ul class="person-list">
                <li class="person" ng-repeat="person in company.users">
                    {{person.firstName}}
                </li>
            </ul>
        </li>
    </ul>

</section>

JavaScript Scripts

var companiesArray = [
    {
        name: 'The Best Company Denim',
        users: [
            {
                firstName: 'Alex',
                lastName: 'D',
                number: 1234
            }, {
                firstName: 'Sarah',
                lastName: 't',
                number: 14
            }, {
                firstName: 'J',
                lastName: 'd',
                number: 07
            }
        ],
    }, {
      ...
    },
];

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

app.controller("myCtrl", function($scope) {
    $scope.companies = companiesArray;
});

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

Guidelines for transferring JavaScript array data to a csv file on the client side

Despite the abundance of similar questions, I am determined to tackle this using JavaScript. Currently, I am utilizing Dojo 1.8 and have all attribute information stored in an array structured like this: [["name1", "city_name1", ...]["name2", "city_name2" ...

Unable to attach the script to recently added DOM elements

After spending considerable time working on this, I'm still unable to figure it out. You can find the page I am referring to at: The "show more" button at the bottom triggers additional posts to be displayed on the page using the following script: ...

JavaScript is a powerful tool for reading JSON files

I'm trying to figure out how to parse a nested object in JSON using JavaScript. Here's the code I have so far: var myRequest = new Request('test.json'); fetch(myRequest) .then(function(response) { return response.json(); }) .then( ...

Specify the dependencies in the package.json file to ensure that the React package designed for React v17 is compatible with React v18 as well

Recently, I developed an npm package using React v17.0.2. The structure of the package.json file is as follows: { "name": "shoe-store", "version": "0.1.0", "private": true, "dependencies": ...

I can't seem to figure out why I keep encountering a runtime error whenever I attempt to create a basic route in the latest version of nextjs, version 13.5

Encountering an error while attempting to create a basic route in app/dashboard/page.tsx. The error message suggests that the contents are not a valid react component, even though they conform to valid react component syntax. Unhandled Runtime Error Erro ...

Angular allows for the utilization of the same URL "/" while serving up distinct templates depending on whether the user is logged in or not

Looking to implement two different templates - one for the landing page for logged out users showcasing the business and another for the dashboard page once a user is logged in. Came across a solution on this particular stack, which explains how to achiev ...

AngularJS: accessing siblings by using the ng-click directive

I am currently working on a list (<ul>), which is being used in multiple instances within different ng-repeat iterations on the same page. The initial list items are generated through ng-repeat, with the second to last item containing a span. When this ...

The code "transform: rotate(' ')" does not seem to be functioning properly in Javascript

I set out to create a simple spin wheel exercise, but it quickly became more challenging than I anticipated. After researching how to make one online, I found code similar to mine that worked on a JSFiddle Example, yet my own code still didn't work. ...

unable to view the contents of the template using the directive

I am facing an issue with the Directive, as it is not adding an element to the Template. This directive has been included in the .html file. There are no errors being displayed in the console. directive.js: app.directive('myDirective', function ...

Reasons Why Vue Component Does Not Update When Select Changes

I'm encountering an issue with a form that is supposed to change text within a vue component based on the selection made in a select box. To demonstrate the problem I'm facing, I've created a simplified version of the code on jsfiddle: http ...

Adding and adjusting the size of different DIV elements within a shared area

Looking to create a dynamic bar with the ability to add multiple child DIVs (similar to this: https://i.stack.imgur.com/tdWsq.jpg). Utilizing jQuery, jQuery UI, Bootstrap, and various plugins. The structure for the div (or span) system could be structured ...

Angular: Issue with click() event not functioning properly once dynamic HTML is rendered

There are a few HTML elements being loaded from the server side, and an Angular click() event is also included. However, the event is not firing after the elements are rendered. It is understood that the DOM needs to be notified, but this cannot be done. ...

Encountering an issue with the default task in gulp, an error is displayed in Gitbash stating: "Task must have a name that is a string

Upon running the command 'gulp' in gitbash, an error is being displayed for the last line of the code, stating: throw new Error('Task requires a name that is a string'); Error: Task requires a name that is a string "use strict"; var g ...

Create a basic cache within an AngularJS service to store data retrieved from HTTP requests, ensuring that the cache returns an object

Looking to implement a simple caching mechanism in an AngularJS service for data retrieved from HTTP requests. The goal is to always reference the same object to avoid duplicating requests. Below is an example code snippet showcasing the issue at hand. Li ...

How to Implement Drupal.behaviors for Specific Pages?

Currently, I have a module that showcases an alert to users within a block. For those interested, you can find my code on GitHub here: https://github.com/kevinquillen/User-Alerts If you would like more information about the module and its functionality, ...

Guide on developing a personalized validation system with Vuetify regulations for verifying the presence of an item

I'm currently working on my first CRUD web app using Vue 2 + Vuetify, but I've hit a roadblock while trying to add validation to a form. Specifically, I need to ensure that no item with the same title already exists in the database. You can view ...

Replicate the process of transferring table rows to the clipboard, but exclusively copying the contents

Currently, I am attempting to copy a paginated table to my clipboard by referring to this guide: Select a complete table with Javascript (to be copied to clipboard). However, the issue lies in the fact that it only copies the data from the first page. In ...

Adjust the tally of search results and modify the selection depending on the frequency of the user's searches within an array of objects

Seeking assistance with adding a new function that allows users to navigate to the next searched result. Big thanks to @ggorlen for aiding in the recursive search. https://i.stack.imgur.com/OsZOh.png I have a recursive search method that marks the first ...

Verify the existence of the email address, and if it is valid, redirect the user to the dashboard page

Here is the code snippet from my dashboard's page.jsx 'use client' import { useSession } from 'next-auth/react' import { redirect } from 'next/navigation' import { getUserByEmail } from '@/utils/user' export d ...

Choose a drop-down menu with a div element to be clicked on using Puppeteer

Issue Description: Currently encountering a problem with a dropdown created using material select. The dropdown is populated through an API, and when selected, ul > li's are also populated in the DOM. Approaches Tried: An attempt was made to res ...