My problem is, on page load, the data received from AJAX may not be ready when the $routeChangeSuccess event fires. In other words, I have a race condition between the event handler and AJAX.
How do I ensure this data is there when the event fires on page load.
Here is a fiddle demonstrating the problem: http://jsfiddle.net/ajrt4/3/
My scenario: I have a select box which is populated by data received by an $http
AJAX call. This select box is used for navigation represents a set of routes the user can select and then go to. Because the select box needs to have the selected option reflect their current route at all times, I use an event handler on the $routeChangeSuccess
event to change the selected drop down when the user uses the back and forward buttons in their browser.
Here is an example of what I have in my controller:
$http.get('getData').success(function(data) {
// Sets the dropdown menu data
$scope.data = data;
});
$scope.$on("$routeChangeSuccess", function(event, currentRoute){
// Set the selected option here based off the route
if (typeof $scope.selected == 'undefined') {
for (var i = 0; i < $scope.data.length; i++) {
if ($scope.data[i].name == $routeParams.name) {
$scope.selected = $scope.data[i]; // sets the current selection based off the route parameter
return;
}
}
}
});
View:
<select ng-model="selected" ng-options="option as option.name for option in data"></select>
The data received needs to be only loaded once so I do not need or want to use resolve
on the $routeProvider
since this used with another controller and view anyway. This also means I will not nest the AJAX call in the event handler and redundantly get the data. What I think might solve this is using the Angular's $q
promise API, but not sure how.