ng-repeat中的ng-init仅显示最后一项信息 [英] ng-init in ng-repeat shows only the last item info
问题描述
我想遍历这样的项目:
<section class="col-sm-4" data-ng-controller="PredictionsController" data-ng-init="findMyPredictions()">
<div class="games">
<div class="game-row" ng-repeat="prediction in predictions" ng-init="getGame(prediction.game_id)">
<a class="button primary alt block" href="#!/predictions/{{prediction._id}}">
<span class="home flag {{gameInfo.team1_key}}"></span>
<span class="middle">
<span class="date">{{gameInfo.play_at | date: 'd.MM HH:mm'}}</span>
<span class="versus">{{gameInfo.team1_title}} - {{gameInfo.team2_title}}</span>
</span>
<span class="away flag {{gameInfo.team2_key}}"></span>
</a>
</div>
</div>
</section>
但是输出只是相同信息的X倍: 尽管请求正确完成:
But the output is just X times the same info: Although the request is done correctly:
你知道这是怎么回事吗?
Any idea what is wrong here?
更新: 我的getGame函数:
UPDATE: My getGame function:
$scope.getGame = function (game_id) {
$scope.gameInfo = {};
$http.get('/games/' + game_id)
.success(function (data) {
$scope.gameInfo = data;
});
};
推荐答案
您每次都覆盖gameInfo
.因此,到渲染时,它只显示最后一个三遍.您需要更像是这样做:
You are overwriting gameInfo
every time. So by the time it renders, it is just showing the last one three times. You need to do it more like:
<div class="game-row" ng-repeat="prediction in predictions" ng-init="getGame(prediction)">
请注意,我们传递的是prediction
对象,而不仅仅是id.然后您可以执行以下操作:
notice we pass in the prediction
object, not just the id. And then you can do:
$scope.getGame = function (prediction) {
prediction.gameInfo = {};
$http.get('/games/' + game_id)
.success(function (data) {
prediction.gameInfo = data;
});
};
然后在HTML中精简而不是gameInfo.whatever
,您将执行prediction.gameInfo.whatever
,这样每个预测都有其自己的变量,并且不会覆盖该变量的单个副本.
And thin in your html, instead of gameInfo.whatever
you will do prediction.gameInfo.whatever
, that way each prediction has it's own variable, and you aren't overwriting your single copy of that variable.
例如:
<span class="date">{{gameInfo.play_at | date: 'd.MM HH:mm'}}</span>
将成为
<span class="date">{{prediction.gameInfo.play_at | date: 'd.MM HH:mm'}}</span>
这篇关于ng-repeat中的ng-init仅显示最后一项信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!