AngularJS ng-show方法被调用太多次 [英] Angularjs ng-show method getting called way too many times

查看:184
本文介绍了AngularJS ng-show方法被调用太多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ng-repeat循环,该循环循环3个事件.在每个事件中,我要检查登录用户是否是该事件所关联的团队的参与者.

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.

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

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>

控制器方法

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

推荐答案

由于数据绑定,ng-show在每个摘要循环中运行.当您从服务器获取事件"的数据时,请考虑在服务器上或在前端对事件进行数据修剪.通常,您需要创建ng-show light函数之类的函数,或者仅与属性中的布尔值相对应.

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.

这篇关于AngularJS ng-show方法被调用太多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆