AngularJS:未捕获错误:[$ rootScope:infdig]

时间:2016-08-08 06:09:02

标签: javascript angularjs

我想为每场比赛赢得所有球场:

HTML看起来像这样:

<div ng-repeat = "g in games">
{{g.gameName}}
<ul>
<li ng-repeat = "c in getCourts(g.id)" ng-bind = "c.courtName"></li>
</ul>
</div>

控制器是:

$scope.games = {};
    $scope.courts = {};
    //$scope.slots = {};

    $http.get(URI+"booking/allGames").then(function success(res){
        $scope.games = res.data;
        //console.log($scope.games);
    },
    function error(res){
        console.log(res.data.message);
    });

    $scope.getCourts = function(gameId){

        //courts = {};
        $http.get(URI+"booking/courts/"+gameId).then(function success(res){

            //console.log(gameId);
            console.log(res.data);
            return res.data;
            //return courts;
        },
        function error(res){
            console.log(res.data.message);
        });;
    }   

当我执行此操作时,我收到此错误:

angular.min.js:6 Uncaught Error: [$rootScope:infdig] 

angularJS文档说,

  

当应用程序的模型变得不稳定时会发生此错误   每个$摘要周期触发状态更改和后续$摘要   周期。

     

一个常见错误是绑定到生成新函数的函数   每次调用时都会出现数组。

我看到了这个答案:AngularJS use a function in a controller to return data from a service to be used in ng-repeat

但我不知道如何解决这个问题。

2 个答案:

答案 0 :(得分:2)

我认为您唯一的选择就是预取这样的所有数据......

$http.get(URI+"booking/allGames").then(res => {
    $q.all(res.data.map(game => {
        return $http.get(URI+"booking/courts/"+game.id).then(res => {
            return angular.extend(game, {courts: res.data});
        });
    })).then(games => {
        $scope.games = games;
    });
});

然后你可以使用嵌套转发器

<div ng-repeat="g in games">
    {{g.gameName}}
    <ul>
        <li ng-repeat="c in g.courts" ng-bind="c.courtName"></li>
    </ul>
</div>

答案 1 :(得分:0)

我推荐菲尔的回答。

这是我的替代方法

注意:我刚刚对数据进行了硬编码以进行演示,您需要在您的情况下调用http

//html
<div ng-controller="MyCtrl">
  <div ng-repeat = "g in games">
  {{g.gameName}}
  <ul ng-init='getCourts(g.id)'>
  <li ng-repeat = "c in courts[$index]" ng-bind = "c.data"></li>
  </ul>
  </div>
</div>

//js

$scope.courts = [];
$scope.games = [
    {
    id:1,
    gameName:'A'
  },{
    id:2,
    gameName:'B'
  },{
    id:3,
    gameName:'C'
  }
];
$scope.getCourts = function(id){
   if(id==1){
     $scope.courts[0]=[{data:'first'},{data:'second'}];
   }else if(id == 2){
     $scope.courts[1]=[{data:'third'},{data:'fourth'}];
   }else{
     $scope.courts[2]=[{data:'five'},{data:'six'}];
   }
}

小提琴:http://jsfiddle.net/Lvc0u55v/8061/