Angularjs ng-show方法被调用方式太多次了

时间:2014-01-03 22:07:58

标签: angularjs

我有一个ng-repeat循环,循环3个事件。在每个事件中,我想检查登录用户是否是与该事件相关联的团队的玩家。

问题是,每次加载页面时,我的代码都会进入is_player()大约30次。这显然会导致问题,因为它试图在不到一秒的时间内完成30次GET方法。

为什么这么多次被调用,我该如何解决这个问题呢?

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

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

控制器方法

/**
     * 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;
    }

1 个答案:

答案 0 :(得分:4)

由于数据绑定,ng-show正在每个摘要周期运行。当您从服务器获取“事件”的数据时,请考虑在服务器或前端对事件进行数据修剪。通常,您希望创建类似于ng-show灯函数的函数,或者只是对应于属性上的布尔值。