Is there something special I need to do to access objects inside $timeout functions?
I get errors saying routes is undefined when I try and access it in the $timeout function, but outside the $timeout function (where the console log is) it logs the object and everything in it is as expected:
$scope.drawRoutes = function(routes) {
console.log(routes);
for (var i = 0; i < routes.length; i++) {
$timeout(function() {
MapService.directionsService.route(routes[i], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
MapService.direction_renderers.push(new google.maps.DirectionsRenderer());
MapService.direction_renderers[MapService.direction_renderers.length - 1].setMap(MapService.gmaps.map);
MapService.direction_renderers[MapService.direction_renderers.length - 1].setDirections(response);
$scope.connectors_created += 1;
$scope.$digest();
}
});
}, 1000);
}
};
Here the problem is the use closure variable
iwithin the timeout callback function... inside each callback instanceirefers to the same closure instance... so when the loop is exitedihas the valueroutes.lengthwhich results in accessingroutes[routes.length]in the callbak which will be undefined.Assuming
routes is an array object, you can use the forEach() iterator function to solve the problem