$ http成功函数外的Angular访问变量

时间:2017-03-17 19:56:55

标签: angularjs json angular-promise angular-http

我试图在实际函数之外循环一些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);
}

});

2 个答案:

答案 0 :(得分:0)

试试这段代码。

go fmt

答案 1 :(得分: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;
});