Candlejack Candlejack - 1 year ago 96
AngularJS Question

Using ng-repeat with the Pokeapi

I'm trying to get the data for two random pokémon from the Pokéapi. I can grab the data fine, but my angular $scope variables are overwriting the first pokémon with the second pokémon, instead of storing both:

$scope.pokemonName =; // only one 'pokemonName' in $scope

You can visually see the pokémon being loaded and displayed incorrectly (two identical pokémon instead of two different ones) in this Plunker example.

I could manually declare two separate $scope variables, eg:


But I want to use ng-repeat in the HTML markup, like this:

<div class='pokemon' ng-repeat="pokemon in pokemonPair">
<h2 class='name'>{{ pokemonName }}</h2>
<img src='{{ pokemonImage }}' />
<!-- etc -->

I feel like what I should be doing, is looping through the required data from the API, then pushing it into a new array of my own creation, and then using my new array in combination with ng-repeat in order to display the two random pokémon. However, I'm unsure as to whether this is an overly convoluted solution. Should I really be re-creating the API data in my own array? It feels like that would be reinventing the wheel. However, I'm not sure how else to solve this problem besides 'Don't use ng-repeat', which isn't a route I want to go down if I can help it, as I'm trying to learn Angular.

Should I be pushing the API data into an array of my own making in order to display it correctly, or is there a smarter way to use ng-repeat?

Answer Source

You are replacing the existing variables, instead of pushing it to an array. Do something like this:

function getStats(pokemonIndex){
    var pokemon = $scope.pokemonPair[pokemonIndex];
            pokemon.pokemonName =;
            pokemon.pokemonExperience =;
            pokemon.pokemonImage =;
            pokemon.pokemonStats =;

            console.log("pokemonName = " + pokemon.pokemonName);

and call it like this:

function populateStats(){
    for (var i = 0; i < $scope.pokemonPair.length; i++){

See this edited plunker

Also notice that I have changed the pokemonPair property to be an array of objects, to be able to add the properties to it and use the ng-repeat.