I am currently working on an AngularJS project in which I have to get project information, for a specific month and year, from the server and show them to the user.
First of all I'm getting a list of Project Id's (projectList), which can be variable, and then I need to get the info on those projects for a specific year and month. With this code I'm trying to get the data and to refresh the data when the last projects is successful. After the data is fetched, I use a ng-repeat to show it to the user.
$scope.getData = function(){
$scope.projectInfoList = [];
for(var index=0; index < $scope.projectList.length; index++){
projectService.getProject($scope.model.year, $scope.model.month, parseInt($scope.projectList[index]) ).success(function(data){
var listInput = { projectID : $scope.projectList[index], data : data};
$scope.projectInfoList.push(listInput);
if(index == $scope.projectList.length - 1){
$scope.$apply();
}
});
};
}
This has 2 mistakes.
I have looked for solutions with $q.all but I'm not sure how I would use it together with variable amount of functions of 'projectService.getProject(..)'
The anonymous callback that you give to the function success
use a closure to the variable index
.
But, your anonymous callback will be called asynchronously (when the call will be done). So when it will be called when index
will be the last index of the array (so here $scope.projectList.length - 1
).
To avoid that, you can use the following pattern:
for(var index=0; index < $scope.projectList.length; index++){
(function (index) {
projectService.getProject($scope.model.year, $scope.model.month, parseInt($scope.projectList[index]) ).success(function(data){
var listInput = { projectID : $scope.projectList[index], data : data};
$scope.projectInfoList.push(listInput);
if(index == $scope.projectList.length - 1){
$scope.$apply();
}
});
})(index)
}
Your second mistake is probably because you change the reference of the array projectInfoList
in your function with $scope.projectInfoList = [];
.
Take a look at this post for more details on this last problem: ng-repeat not updating on update of array