Reputation: 1734
I am trying to get all the courts for each game:
The HTML looks like this:
<div ng-repeat = "g in games">
{{g.gameName}}
<ul>
<li ng-repeat = "c in getCourts(g.id)" ng-bind = "c.courtName"></li>
</ul>
</div>
The controller is :
$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);
});;
}
When I execute this, I getting this error:
angular.min.js:6 Uncaught Error: [$rootScope:infdig]
The angularJS documentaion says,
This error occurs when the application's model becomes unstable and each $digest cycle triggers a state change and subsequent $digest cycle.
One common mistake is binding to a function which generates a new array every time it is called.
I saw this answer : AngularJS use a function in a controller to return data from a service to be used in ng-repeat
But I am not sure how to fix this.
Upvotes: 4
Views: 6751
Reputation: 3892
I do recommend Phil's answer.
Here is my alternate approach
Note: I just hardcoded the data for demonstration, you need to call http in your case
//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'}];
}
}
fiddle: http://jsfiddle.net/Lvc0u55v/8061/
Upvotes: 0
Reputation: 165059
I think your only option is to pre-fetch all the data like this...
$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;
});
});
Then you can just use a nested repeater
<div ng-repeat="g in games">
{{g.gameName}}
<ul>
<li ng-repeat="c in g.courts" ng-bind="c.courtName"></li>
</ul>
</div>
Upvotes: 2