将对象传递给$ timeout

时间:2013-09-30 02:29:01

标签: angularjs angularjs-scope angularjs-timeout

在$ timeout函数中访问对象需要做些什么特别的事情吗?

当我尝试在$ timeout函数中访问路径时,我得到错误,说明路由是未定义的,但在$ 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);
   }
};

1 个答案:

答案 0 :(得分:5)

这里的问题是在超时回调函数中使用闭包变量i ...每个回调实例i内部引用相同的闭包实例...所以当循环退出时{{ 1}}的值为i,导致访问调用块中的routes.length,这将是未定义的。

假设routes[routes.length]是一个数组对象,你可以使用forEach()迭代器函数来解决问题

route
相关问题