I ma developing an app with Steroids/Supersonic using Parse as back-end and I am struggling to make object relationships work. Here an example. I have one class Course and one class Teacher with a one to one relationship (each Course one Teacher). What I would like to do is to display all the courses with the associated teacher. To set up the relationship in Parse I have used a column type "Pointer" to the other class. Below the code in the controller:
Course.findAll().then( function (courses) {
$scope.$apply( function () {
$scope.courses= courses;
for (i = 0; i < $scope.courses.length; i++) {
// look for the teacher
Teacher.find($scope.courses[i].Teacher.objectId).then( function (teacher) {
$scope.$apply( function () {
$scope.courses[i].Teacher= teacher;
});
});
}
});
});
The problem of the above code is that the variable "i" is not defined inside the Teacher.find() function so I cannot assign the teacher object to the correct course object. I even tried to use a specific variable in the scope to manage the index as in this other code:
Course.findAll().then( function (courses) {
$scope.$apply( function () {
$scope.courses= courses;
$scope.index = 0
for (i = 0; i < $scope.courses.length; i++) {
// look for the teacher
Teacher.find($scope.courses[i].Teacher.objectId).then( function (teacher) {
$scope.$apply( function () {
$scope.courses[$scope.index].Teacher= teacher;
$scope.index = $scope.index + 1
});
});
}
});
});
The problem of this second code is that randomly a teacher is linked to the wrong course maybe because the function find() is called asynchronous so the two variables i and index are not always synchronized.
I believe the problem I am facing is more related to the asynchronous behavior of angularjs but I don't really know how to solve it. Thanks for your help!