2013-09-30 30 views
1

是否有什么特殊的我需要做的来访问$ timeout函数内的对象?

我得到的错误说的路线是不确定的,当我试图访问它在$超时功能,但$超时功能(其中控制台日志)之外它记录的对象,一切都在不出所料:

$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); 
    } 
}; 

回答

5

这里的问题是在超时回调函数内使用闭合可变i ...各回调实例内i指同一闭合实例...所以当循环被退出i具有这导致值routes.length在未定义的callbak中访问routes[routes.length]

假设route s是一个数组对象,则可以使用在foreach()迭代函数来解决问题

$scope.drawRoutes = function (routes) { 
    console.log(routes); 
    angular.forEach(routes, function (route, idx) { 
     $timeout(function() { 
      MapService.directionsService.route(route, 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(); 
       } 
      }); 
     }, (idx + 1) * 1000); 
    }) 
}; 
+0

谢谢,做到了。我也意识到我的方法没有意义。我试图每隔1秒渲染一条新路由,但是我的方法等待1秒钟,然后渲染所有这些路由,因为所有超时都在毫秒之内调用:-( – andro1d

+0

@ andro1d在这种情况下尝试更新 –

+0

再次感谢,你是冠军!:-) – andro1d