My issue involves a firebaseObject (MyFirebaseService.getCurrentUser()) being bound to $scope.user. Once successfully bound, I iterate through the object to check if it contains an "associatedCourseId" equal to a specific value ($stateParams.id). If it does, the $scope.finishLessonCount increases. The problem arises when I add a new Object to the firebaseObject (bound to user) from another page or within firebase itself, as the finishLessonCount value does not update as expected with 3-way binding. I have to refresh the page in order to see the finishLessonCount reflect the correct value. I want the finishLessonCount to change automatically using the compare function whenever more finishedLessons are added to the firebaseObject. Here is my code snippet:
MyFirebaseService.getCurrentUser().$bindTo($scope, "user").then(function(){
for (var key in $scope.user.finishedLessons) {
if ($scope.user.finishedLessons.hasOwnProperty(key)) {
if ($scope.user.finishedLessons[key].associatedCourseId == $stateParams.id) {
$scope.finishLessonCount++;
}
}
};
console.log ($scope.finishLessonCount);
});
UPDATE 1 based on @Kato's suggestion: I attempted to resolve this issue by extending the firebaseObject method, but unfortunately that did not work either. To simplify and avoid using factory, I needed to pass in the courseId for the operation. Below is the updated code:
function countLessons(lessons, courseId) {
var count = 0;
for(var key in lessons) {
if( lessons[key].associatedCourseId == courseId) {
count++;
}
}
return count;
}
var UserWithLessonsCounter = $firebaseObject.$extend({
$$updated: function(snap) {
var changed = $firebaseObject.prototype.$$updated.call(this, snap);
this.lessonCount = countLessons(this.finishedLessons, $stateParams.id);
}
});
var refTemp = new Firebase($rootScope.baseUrl + "users/" + $rootScope.userId);
var userTemp = new UserWithLessonsCounter(refTemp);
userTemp.$bindTo($scope, "userTemp").then(function(){
console.log($scope.userTemp);
});
userTemp.$watch(function() {
console.log("Does this run at all? " + $scope.userTemp.lessonCount);
});
Even after updating the user object, the lessonCount value remains unchanged unless I refresh the page. Additionally, the console.log statement inside the $watch function does not execute at all. What could be causing this issue?