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

标签 angularjs

这个问题在这里已经有了答案:





Is expression inside ng-show fired after every model change in AngularJS?

(2 个回答)


8年前关闭。




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

问题是,我的代码进入了 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>

Controller 方法
/**
     * 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由于数据绑定(bind),每个摘要周期都在运行。当您从服务器获取“事件”的数据时,请考虑在服务器或前端对事件进行数据修剪。通常,您希望创建像 ng-show light 函数这样的函数,或者只是对应于属性上的 bool 值。

关于Angularjs ng-show 方法被调用太多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20913569/

相关文章:

javascript - AngularJS - 使用服务方法的结果更新 DOM

Java 字符串到日期到不同字符串格式

javascript - 跟踪用户输入并提供单词完成- Angular

javascript - 使用 ng-repeat 在 AngularJS 中鼠标悬停时激活 .gif

javascript - 在 angularjs 中使用 office-ui-fabric-js

javascript - Restangular - 如何获得请求的普通结果(未包装)

angularjs - Angular-ui模态,从$ http将数据发送到模态 Controller

angularjs如何根据index.html中的路由设置&lt;script src ="controller">

angularjs - 如何从 angular 资源中获取完整的响应头

javascript - CouchDB 中的 JSON 行为