Loop through array objects using ng-repeat in AngularJS

Trying to figure out how to iterate through an array using ngrepeat.

If I have an array of data like this:

{
  "People": [{
      "name": "Andrew Amernante",
      "rating": 3,
    },
    {
      "name": "Frank Wang",
      "rating": 5,
    },
    {
      "name": "Chang Wang",
      "rating": 5,
    }
  ]
}

In my Controller, I have the following code snippets:

app.controller('mainController', function($scope, $http) {
  $http.get('people.json').
  then(function onSuccess(response) {
    console.log(response);
    $scope.peoples = response.data;

  }).
  catch(function onError(response) {
    console.log(response);
  });
});

I want to iterate through the array and display the three names in a list.

<ul class="nav">
  <li ng-repeat="person in peoples track by $index">
    <a href="#/">{{person.name}}</a>
  </li>
</ul>

However, I'm having trouble getting the names to display. Any ideas on what might be going wrong?

For your information, I am using Angular version 1.6.5 here.

Plunkr with the full code provided.

Answer №1

Your HTML code needs some fixing.

Change

ng-repeat="obj.peoples track by $index"
to
ng-repeat="obj in peoples.People track by $index"

Check out the demonstration below.

angular.module('app', [])
          .controller('mainController', function($scope, $http) {
            // mocked data similar to `$scope.peoples = response.data`
            $scope.peoples = {
              "People": [{
                  "name": "Andrew Amernante",
                  "rating": 3,
                },
                {
                  "name": "Frank Wang",
                  "rating": 5,
                },
                {
                  "name": "Chang Wang",
                  "rating": 5,
                }
              ]
            };
          });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='mainController'>
  <ul class="nav">
    <li ng-repeat="obj in peoples.People track by $index">
      <a href="#/">{{obj.name}}</a>
    </li>
  </ul>

</div>

Answer №2

the script.js file contains information about people, while the obj is used in the html code.

$http.get('people.json').
        then(function onSuccess(response) {
            console.log(response);
            $scope.peoples = response.data;

        }).

Update your html with the following code:

<li class="active" ng-repeat="item in peoples.People">
       <a href="#/">{{item.name}}<span class="glyphicon glyphicon-play"></span></a>
 </li>

Answer №3

There are two important steps in JavaScript

 $scope.peopleList = response.data.People;

When using ng-repeat, it is crucial to have this syntax:

ng-repeat="person in peopleList track by $index"

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

Leveraging partials on their own

I am currently exploring the possibility of loading a partial in linkedin-dustjs without having to load its parent along with it. For instance, consider this partial (login.dust): {>layout/} {<content} <!-- Login Screen --> {/content} Th ...

moving all duplicate elements in an array into a separate array

I am struggling to achieve the result [1,1,1,1,2,2,20,20] from the given array. My goal is to extract all duplicate values into a new array, but I just can't seem to get it right. Can you please assist me? const array = [1, 2, 4, 591, 392, 391, 2, ...

Organize pairs of strings into a nested array within an array using Angular

Currently, I am working on a project in Angular. In this project, I have a string that contains special characters which I have successfully removed using regular expressions. Now, my goal is to arrange the first two strings within square brackets and the ...

"Ensuring Mongoose pre-save functionality correctly enhances field without triggering updates

I am working with a Video schema that looks like this: const videoSchema = new mongoose.Schema({ cover: { // image url type: String, required: true, }, category: [{ type: mongoose.Schema.Types.ObjectId, ref: &apo ...

Loading data into a Dojo ItemFileReadStore using Grails and the "render as JSON" method

I have developed a controller method that generates a JSON "file" on-the-fly when the corresponding URL is accessed. This file exists in memory and not saved on disk, as it's dynamically created when the URL is hit. I'm attempting to utilize this ...

What could be causing the parsing issue on the page for Node.js?

When attempting to access the given page with invalid credentials: In a browser, I receive well-formatted JSON: { "error": { "code": "request_token_invalid", "message": "The access token isn't valid." } } However, trying the equi ...

Troubleshooting the issues with testing AngularJS using Jasmine and Karma, particularly when $httpBackend is

I'm currently in the process of writing unit tests for my Angular app using Jasmine with Karma. One of the functionalities of the app is to make a call to the GitHub API, retrieve a user's repository names, and store them in an array. Although I& ...

Error: The component is unable to access this.props.match because it is undefined

Currently, I am in the process of designing a dashboard that will allow users to modify records and perform other actions. I have implemented edit and delete buttons that direct users to the appropriate routes. The challenge arises when accessing the edi ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

Why is an array converted to a pointer instead of a reference when using auto?

Take a look at the example below: int arr[10]; int *pointer = arr; // This is the first valid choice int (&reference)[10] = arr; // This is the second valid choice When we use auto with arr, it selects the first choice. auto x = arr; // x is equival ...

Unlocking the potential of GraphQL: Harnessing the power of sibling resolvers to access output from another

Could use a little assistance. Let's say I'm trying to retrieve the following data: { parent { obj1 { value1 } obj2 { value2 } } } Now, I need the result of value2 in the value1 resolver for calculation ...

The Meteor update is unsuccessful on the Mongo Sub Collection and will not continue

I am currently facing an issue with updating a specific object within an array in my object based on a value. Whenever I try to add the update code, the function gets stuck at that point without proceeding further. None of the console.log calls after the u ...

Exploring the Differences Between Copying and Editing Java Arrays

When we assign an array to another variable, it essentially points to the same array with a new name. To make a copy of an array, we must either manually copy each element or use a method from a programming language package. public class puzzle { pub ...

ul insertBefore causes a Uncaught TypeError to be thrown

Greetings! I must confess that I am still learning the ropes of JS and Stack Overflow, so please bear with me if my question sounds amateur. Currently, I am in the process of developing a todo list application that comprises multiple todo lists. One of the ...

Is there a way for my script to interpret a subscripted output as a predefined variable name?

Is there a way to make the output of my string be interpreted as a variable rather than displayed as text? Despite researching the issue, I am struggling to find a solution as a beginner in this subject. } function showDetailedView(currentDiv) { var ...

Reserve Your Room in Style with C++!

Seeking assistance with the Hotel Bookings Problem C++ from InterviewBit website. I've been struggling to find a solution to this particular question. The scenario is as follows: A hotel manager needs to process N advance bookings for rooms for an upc ...

Using Javascript to dynamically add variables to a form submission process

Looking to enhance my javascript skills, I've created a script that locates an existing id and exchanges it with a form. Inside this form, I'm aiming to incorporate javascript variables into the submit url. Unsure if this is feasible or if I&apo ...

Tips for using jQuery to load JSON data from a backing bean within a customized JSF component

What is the most efficient way in JSF 2.2 to load JSON data from a backing bean into a JavaScript program that runs in a browser? Currently, I am transitioning a messy, iframed visjs network graph to JSF 2.2 - Primefaces 6.1. All our custom UI components ...

Tips on displaying each element of an array in a unique format within a React component

I am working on creating a component that will display data in boxes. Each set of constant data should be placed within a div for organization. Currently, I have a Box component that is responsible for displaying the data. The Tutorial component receives ...

utilizing the identical characteristics of the parent component

In order for the properties in InputGroup.js to be accessible as this.props in lower-level components like TextInput.js, Checkbox.js, I have created a simple component called InputComponent.js. In this component, I assign this.props to this.prpt so that it ...