Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

angularjs - ng-init in ng-repeat shows only the last item info

I want to loop through items like this:

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

But the output is just X times the same info: enter image description here Although the request is done correctly: enter image description here

Any idea what is wrong here?

UPDATE: My getGame function:

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

};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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;
  });
};

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.

For example:

<span class="date">{{gameInfo.play_at | date: 'd.MM HH:mm'}}</span>

would become

<span class="date">{{prediction.gameInfo.play_at | date: 'd.MM HH:mm'}}</span>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...