我正在尝试从Pokéapi获取两个随机口袋妖怪的数据。我可以很好地获取数据,但是我的angular $scope变量正在用第二个精灵覆盖第一个精灵,而不是同时存储两个精灵:
$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-repeat结合使用,以便显示两个随机的神奇宝贝。然而,我不确定这是否是一个过于复杂的解决方案。我真的应该在我自己的数组中重新创建API数据吗?这感觉就像是在重新发明轮子。然而,除了“不要使用ng-repeat”之外,我不确定如何解决这个问题,如果可以的话,这不是我想要走的路线,因为我正在努力学习Angular。
为了正确显示数据,我应该将API数据放入自己创建的数组中吗?或者有没有更聪明的方法来使用ng-repeat?
发布于 2016-09-20 20:36:29
您将替换现有变量,而不是将其推入数组。这样做:
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);
}
}还要注意,我已经将pokemonPair属性更改为一个对象数组,以便能够向其中添加属性并使用ng-repeat。
发布于 2016-09-20 20:42:44
您必须阅读有关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.
});发布于 2016-09-20 20:46:41
下面是一个有效的柱塞: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);
});
}https://stackoverflow.com/questions/39594087
复制相似问题