使用angular.js的For循环中的Javascript闭包(涉及两个闭包-一个$http.get调用和一个$scope.watch)

使用angular.js的For循环中的Javascript闭包(涉及两个闭包-一个$http.get调用和一个$scope.watch),javascript,angularjs,google-maps,anonymous-function,iife,Javascript,Angularjs,Google Maps,Anonymous Function,Iife,我正在使用创建一个角度应用程序。我要做的是循环遍历一组位置,以便在每个位置的纬度和经度上放置一个标记。但是,因为我在for循环中使用了几个闭包,所以标记只出现在数组的最后一个条目上。代码如下: $scope.petMarkers = []; $http.get('/api/pets').success(function(foundPets){ $scope.foundPets = foundPets; var listOfPets = $scope.foundPets; var ma

我正在使用创建一个角度应用程序。我要做的是循环遍历一组位置,以便在每个位置的纬度和经度上放置一个标记。但是,因为我在for循环中使用了几个闭包,所以标记只出现在数组的最后一个条目上。代码如下:

$scope.petMarkers = [];
$http.get('/api/pets').success(function(foundPets){
  $scope.foundPets = foundPets;
  var listOfPets = $scope.foundPets;
  var markerCreator = function(arrayOfPets){
    for (var i = 0; i < arrayOfPets.length; i++){
      var singlePet = arrayOfPets[i];
      var petName = arrayOfPets[i].name;
      var identity = singlePet._id;
      var location = singlePet.addressFound;
      var split = location.split(' ');
      var joined = split.join('+');
      var httpAddress = 'http://maps.google.com/maps/api/geocode/json?address=' + joined + '&sensor=false';

      // anonymous function keeps reference to i, and when console.log is called, for loop has already finished and value of i is set to 4
      $http.get(httpAddress).success(function(mapDataAgain){
        var ladder = mapDataAgain.results[0].geometry.location.lat; 
        var longer = mapDataAgain.results[0].geometry.location.lng;
        var obj = {
          latitude: ladder,
          longitude: longer,
          title: petName,
          id: i
        };
        $scope.$watch(function(){
          console.log('we are in scope.watch');
          return $scope.map.bounds;
        }, function(){
          var markers = [];
          //markers.push(obj);
          $scope.petMarkers.push(obj);
          //$scope.petMarkers = markers;
          console.log('markers = ', $scope.petMarkers);
        }, true);
      });
    };
  };
  markerCreator(listOfPets);
});
$scope.petMarkers=[];
$http.get('/api/pets').success(函数(foundPets){
$scope.foundPets=foundPets;
var listOfPets=$scope.foundPets;
var markerCreator=函数(arrayOfPets){
对于(变量i=0;i