将对象传递给$ timeout

and*_*o1d 1 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);
   }
};
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 5

这里的问题是i在超时回调函数中使用闭包变量...每个回调实例内部i引用相同的闭包实例...因此当退出循环时,i该值routes.length导致在routes[routes.length]callbak 中访问将被取消定义.

假设routes是一个数组对象,您可以使用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);
    })
};
Run Code Online (Sandbox Code Playgroud)