这个问题在这里已经有了答案:
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/