4

I have an ng-repeat loop which loops over 3 events. In each event, I want to check to see if the logged in user, is a player of the team the event is associated with.

The problem is, my code is getting inside is_player() around 30 times each time the page is loaded. This obviously causes problems because it's trying to hit the GET method like 30 times in less than a second.

Why is this being called so many times and how can I fix this issue?

<div class="list-group" ng-repeat="event in events">

     <div ng-show="is_player(event.team_id, profile.id)">
         ...
     </div>
</div>

Controller method

/**
     * Checks if a user is a player on the team. Need this method so that managers of a team can't rsvp if they're only a manager and not a player
     * @param team_id   - The team id of the event that we want to check if the user plays on
     * @param user_id   - The user that we want to check if they're a player of a team
     */
    $scope.is_player = function(team_id, user_id) {

        console.log('in is_player');

            $http.get(baseUrl+'v1/teams/' + team_id + '/players' + apiKey)
                .success(function(response) {

                    console.log("getting a team's players");
                    var players = response;

                    // Loop through all the players on the team
                    for(var i = 0; i < players.length; i++) {

                        //If the current player in the loop's user id matches what was passed in
                        if(players[i].user.id == user_id) {
                            return true;
                        }
                    } 

                    $scope.error = null;
                })
                .error(function(response) {
                    $scope.success = null;
                    $scope.error = 'An error occurred looking for your events. Please try again later.';
                }); 

        return false;
    }
Catfish
  • 17,987
  • 50
  • 195
  • 342

1 Answers1

4

the ng-show is being run on every digest cycle because of the data binding. Consider doing data pruning of events, either on the server or on the front end when you get the data back of "events" from the server. In general, you want to make functions like ng-show light functions, or simply correspond to boolean values on a property.

victormejia
  • 1,164
  • 2
  • 12
  • 30