ng-repeat中的ng-init仅显示最后一项信息

时间:2014-06-11 21:18:45

标签: angularjs angularjs-ng-repeat angularjs-ng-init

我想循环使用这样的项目:

<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倍: enter image description here 虽然请求正确完成: enter image description here

知道这里有什么问题吗?

更新: 我的getGame函数:

$scope.getGame = function (game_id) {
    $scope.gameInfo = {};
    $http.get('/games/' + game_id)
    .success(function (data) {
        $scope.gameInfo = data;
    });

};

1 个答案:

答案 0 :(得分:7)

您每次都会覆盖gameInfo。因此,当它呈现时,它只是显示最后一次三次。你需要做的更像:

<div class="game-row" ng-repeat="prediction in predictions" ng-init="getGame(prediction)">

注意我们传入prediction对象,而不仅仅是id。然后你就可以做到:

$scope.getGame = function (prediction) {
  prediction.gameInfo = {};
  $http.get('/games/' + game_id)
  .success(function (data) {
    prediction.gameInfo = data;
  });
};

在你的html中,而不是gameInfo.whatever,你会做prediction.gameInfo.whatever,这样每个预测都有它自己的变量,你不会覆盖你的单个副本那个变量。

例如:

<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>