Why is my res.data returning an array of objects in AngularJs?

I've been working on integrating an API with AngularJS and trying to display the data using ng-repeat, but I'm facing challenges in accessing the object's information.

Below is the feedback I received:

(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

0: {name: 'bulbasaur', url: 'https://pokeapi.co/api/v2/pokemon/1/'}

1: {name: 'ivysaur', url: 'https://pokeapi.co/api/v2/pokemon/2/'}

2: {name: 'venusaur', url: 'https://pokeapi.co/api/v2/pokemon/3/'}

3: {name: 'charmander', url: 'https://pokeapi.co/api/v2/pokemon/4/'}

...and more

$$hashKey: "object:3" length: 20

<script>
        angular.module('Pokedex', []).controller('myController', function ($scope, $http) {
            $scope.pokemons = []

            let getPokemons = function () {
                $http.get('https://pokeapi.co/api/v2/pokemon/?offset={qtd')
                    .then(function (res) {
                        let pokemon = res.data.results
                        console.log(pokemon)
                        $scope.pokemons.push(pokemon)
                    })
            }
            getPokemons()
        })
    </script>
<body ng-controller="myController" ng-app="myapp">
    <div>
        <ul>
            <li ng-repeat="pokemon in pokemons">
                <h2>{{ pokemon.name }}</h2>
            </li>
        </ul>
    </div>

I am currently only able to access the name by doing `pokemon[0].name`. I attempted to use map to access the array data, but faced difficulties due to being unfamiliar with this version of Angular. Can anyone point out where I might be going wrong?

Answer №1

Make sure to assign the array of responses from your API call to $scope.pokemons.

If you simply push the API response into the $scope.pokemons array as is, all the data will be stored under $scope.pokemons[0], making it difficult to iterate through using ng-repeat in your template.

View Working Example Below:

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
  $scope.pokemons = []

  let getPokemons = function () {
    $http.get('https://pokeapi.co/api/v2/pokemon/?offset={qtd')
      .then(function (res) {
        let pokemon = res.data.results
        console.log(pokemon)
        $scope.pokemons = pokemon;
      })
  }
  getPokemons()
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div>
    <ul>
      <li ng-repeat="pokemon in pokemons">
        <h2>{{ pokemon.name }}</h2>
      </li>
    </ul>
  </div>
</div>

Answer №2

You must use the ng-repeat directive within another ng-repeat.

Here is an example for your reference:

<ul ng-repeat="pokemon in pokemons">
    <li ng-repeat="(key, value) in pokemon">
        <h2>{{ value.name }}</h2>
    </li>
</ul>

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

Getting the most out of Nexmo with multiple websocket connections

I have integrated the code provided by Nexmo (shown below) into my server. However, I am facing an issue where if two callers ping my server, the binary data from the second caller also streams into the same websocket endpoint, resulting in two binary st ...

Tips for preventing Unknown event codes in POST request responses

When my client makes POST requests to the nodejs server I am running, I receive "unknown event 72" messages in the POST response, as shown in the Wireshark screenshot below. These extra data points are causing unnecessary bandwidth usage for my application ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

Assigning values to props in a Vue component

I created a Vue component that is supposed to receive the "uploadedFile" prop, but it's not functioning properly. I am only getting the correct information in the $attrs: https://i.sstatic.net/crXmH.png Here is my component: Vue.component('t ...

Names picked at random and presented in the innerHTML

I am currently working on a project that involves displaying random names from an array in a text area named "textbox". Currently, I am using math.random() to pick a name randomly, but it only generates a new random name when the page is reloaded. How ca ...

Transferring data from Angular to Django form

I'm having an issue with sending data from AngularJS to a Django backend. Below is the code snippet causing the problem: Angular $http({ method: 'POST', url: 'path/to/django/', data: $scope.formData, headers: { ...

What is the best way to embed PHP code into a jQuery append using AJAX?

After searching for information on "How to insert PHP into jQuery?", I have not been able to find the solution that I need. I have a todo list in php and I am trying to implement ajax functionality into it. When the ajax call is successful, I want to appen ...

Adding a JavaScript script tag within a React app's ComponentDidMount - a guide

I am currently in the process of implementing Google Optimize on my website. I need to include the following script tag within my page: <script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date; h.end=i=function(){s.classN ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

Issue arised while trying to open Bootstrap modal window due to conflict with surrounding elements

I'm facing a challenge with getting the bootstrap modal window to pop up on my website. Despite trying various solutions and troubleshooting steps, I haven't been able to resolve the issue. Even after eliminating all scripts except for the boots ...

Adjust the cell text overflow based on the width of the table

I am working with a table that has multiple columns. I want the first 3 columns to have a larger width than the others, specifically taking up 15% each for a total of 45% of the table's width. Currently, I am using this code in a sandbox environment: ...

I am having trouble getting Vue.js to function properly within HTML when using Django. Can someone please lend me a

The code run Here is the HTML document: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <!--javascript extensions--> <script src=' ...

Is it possible to utilize the key from ng-repeat within a model for another purpose?

Is there a way to use the ng-repeat key as part of the ng-model for an input field in AngularJS? Here is an example of what I am trying to achieve: <div ng-repeat="(key, val) in $ctrl.offer.properties"> <fieldset ng-if="val"> <h3> ...

Utilize AJAX/JS and Django to seamlessly upload files

This is the form for my popup window. <div class="popup media-upload-form"> <div class="border cf"> <div class="close">X</div> </div> <form class="cf" action="" method="POST" enctype="multipart/form-data"> ...

Passing arguments to the callback function in React: a comprehensive guide

Within my react component, I have a collection of elements that I want to make clickable. When clicked, I trigger an external function and pass the item ID as an argument: render () { return ( <ul> {this.props.items.map(item => ( ...

Creating input fields using Vuejs

Currently, I am learning how to incorporate HTML content rendering in Vuejs. I'm experimenting with creating a small input component that is generated through the render function. Here is a snippet of what I have so far: export default { name: &qu ...

Is there a way to prevent the Alt+F4 function from closing tabs in the Internet Explorer browser

Ctrl+W and Alt+F4 can be used to close the IE browser, but I am looking to disable this default action. While I have found a way to handle the Ctrl+W command, I am struggling with disabling the Alt+F4 event. It seems that other Alt+Key events like Alt+En ...

Concealing option value based on ng-if conditions in AngularJS: A guide

I am designing an Input form with two input fields that need to be compared and values displayed if a certain condition is met. The input fields are: <td class="td_label"><label>Client Age :</label></td> <td class="td_input"> ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

HTML5 Canvas Border

Hey Everyone, I've been working on an HTML5 canvas project where I set the canvas width to $(window).width(). Everything was going smoothly until I added a border, which caused a horizontal scroll to appear. Important: I attempted to use the innerWid ...