I am a bit stuck trying to figure out how to apply $digest() or $apply() to update bindings.
I have done a bit of reading on other threads and I think the concept makes sense. However, I am unable to apply it to my specific context. This could mean that my approach thus far is flawed...
Here is my situation:
- I have two dropdowns: School and Teacher
- When the page is loaded, the School dropdown populates based on data returned from a service
- When you select a school, the Teacher service fires and returns a list of teachers
- Unfortunately, the teacher dropdown doesn’t populate with the new teacher list
- If I click to another routed page and then click back, the new teacher list is available
Here is my MainController:
app.controller('MainController', function ($scope, $timeout, schoolService, teachersService) {
var self = this;
self.teachers = teachersService.teachers;
self.schoolSelected = function () {
setTimeout(function () {
teachersService.goGetTeachers($scope.sessionKey);
console.log(self.teachers);
$scope.$apply();
}, 5);
};
}
When schoolSelected is triggered, it executes the teachersService. The returned data logs to console. I receive no errors.
However, it does not update self.teachers. When console.log(self.teacher) is run within the schoolSelected function, it returns "undefined."
I think this is an issue with synchronicity and that the console.log(self.teacher) and the $scope.$apply() are both running before the service has completed.