在 Pokeapi 中使用 ng-repeat

Using ng-repeat with the Pokeapi

我正在尝试从 Pokéapi 中获取两个随机神奇宝贝的数据。我可以很好地获取数据,但是我的 angular $scope 变量正在用第二个 pokémon 覆盖第一个 pokémon,而不是同时存储两者:

$http.get(endPoint)
    .then(function(res){
        $scope.pokemonName = res.data.name; // only one 'pokemonName' in $scope
});

您可以直观地看到神奇宝贝被加载和显示不正确(两个相同的神奇宝贝而不是两个不同的)in this Plunker example

我可以手动声明两个单独的 $scope 变量,例如:

$scope.pokemonNameOne;
$scope.pokemonNameTwo;

但我想在 HTML 标记中使用 ng-repeat,如下所示:

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

我觉得我应该做的是循环遍历 API 中的所需数据,然后将其推入我自己创建的新数组,然后将我的新数组与 ng 结合使用-重复以显示两个随机神奇宝贝。但是,我不确定这是否是一个过于复杂的解决方案。我真的应该在自己的数组中重新创建 API 数据吗?感觉那将是重新发明轮子。但是,我不确定除了“不要使用 ng-repeat”之外还有什么方法可以解决这个问题,如果我可以帮助的话,这不是我想走的路,因为我正在努力学习 Angular.

我应该将 API 数据推送到我自己制作的数组中以便正确显示它,还是有更聪明的方法来使用 ng-repeat?

您正在替换现有变量,而不是将其推送到数组。做这样的事情:

function getStats(pokemonIndex){
    var pokemon = $scope.pokemonPair[pokemonIndex];
    $http.get(pokemon.endPoint)
        .then(function(res){
            pokemon.pokemonName = res.data.name;
            pokemon.pokemonExperience = res.data.base_experience;
            pokemon.pokemonImage = res.data.sprites.front_default;
            pokemon.pokemonStats = res.data.stats;

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

并这样称呼它:

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

this edited plunker

另请注意,我已将 pokemonPair 属性 更改为对象数组,以便能够向其添加属性并使用 ng-repeat.

您必须阅读 JavaScript 中有关数组的内容。您的问题实际上与 Angular 本身无关。

    $scope.pokemonNames = [];
    $http.get(endPoint)
    .then(function(res){
        var pokemon = {};
        pokemon.name = res.data.name;
        pokemon.attribute = res.data.attribute;
        $scope.pokemonNames.push(pokemon); // then iterate over pokemonNames array in ng-repeat.
});

这是一个有效的插件: https://plnkr.co/edit/c5seK6wr8rQjMAj5GZA9?p=preview

只需将 api 的响应推送到一个数组中,并从那里对所有内容进行数据绑定!

function getStats(endPoint){
        $http.get(endPoint)
          .then(function(res){
            $scope.pokemons.push(res.data);
            console.log("pokemonName = " + $scope.pokemonName);
        });
    }