2017-03-17 2 views
0

私は実際の関数の外でいくつかのjson値をループしようとしています。誰も私を助けることができる?

app.controller('MapCtrl', function($scope, $http){ 

$scope.contents = []; 

$http.get('/data4estate/data_model.php') 
    .success(function(data) { 
     $scope.contents = data; 
    }); 

for (i = 0; i < $scope.contents.length; i++) { 
    console.log($scope.contents[i].name); 
} 

});

+0

'$ http'' $のscope.contents'が取り込まれているの前に実行されているループのために、非同期れます。 –

+3

[非同期呼び出しからの応答を返すにはどうすればよいですか?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

+0

意味を理解していない –

答えて

0

このコードを試してください。

app.controller('MapCtrl', function ($scope, $http) { 

     $scope.contents = []; 

     $http.get('/data4estate/data_model.php') 
      .success(function (data) { 
       $scope.contents = data; 
      }); 

     $scope.$watch('contents', function() { 
      for (i = 0; i < $scope.contents.length; i++) { 
       console.log($scope.contents[i].name); 
      } 
     }); 
    }); 
+0

[$ HTTPの成功/エラーの方法は推奨されないのはなぜですか?]を参照してください。 v1.6から削除されましたか?](http://stackoverflow.com/questions/35329384/) – georgeawg

0
$http.get('/data4estate/data_model.php').then(function(response) { 
    angular.forEach(response.data, function(dataItem) { 
     console.log(dataItem); 

    }); 
    /*once you assign the result to $scope here, all the bindings 
     in your view will update automatically */ 
    $scope.contents = response.data; 
}); 
関連する問題