2016-04-26 43 views
1
app.controller('tableController', function ($scope, $filter, ngTableParams,$http){ 

    $scope.users = []; 

    $http.get("getjsondata").success(function (response) { 
     $scope.users = response; //ajax request to fetch data into $scope.data 
    }); 

    console.log($scope.users); // I am not getting the updated value as 
           // I need to pass this value in another function 
}); 
+0

首先检查你正在从JSON你越来越响应和检查浏览器控制台,如果你得到任何错误的任何数据。您还可以调试您的Angular代码以检查响应的值是多少 – user3045179

+1

可能的重复[如何从异步调用返回响应?](http://stackoverflow.com/questions/14220321/how-do-i -return-the-a-response-from-an-asynchronous-call)由于'response'只在异步请求完成后才可用,所以不能在'console.log'中出现。 –

回答

1

console.log语句被执行您发出HTTP请求之后。

您需要在您的成功回调中记录/与它进行交互。

$http.get("getjsondata").success(function (response) { 
    $scope.users = response; 
    console.log($scope.users); 
}); 

此外,尽量不要在您的控制器中使用$scope。请参阅John Papa's style guide for Angular.js

3

成功后的功能模态值调用后回调完成后,如果你想看到你必须调用任何其他功能或通过内部的任何值值回调

$scope.users = []; 
$http.get("getjsondata").success(function (response) { 
    $scope.users = response; 
    console.log($scope.users); 
}); 
1

您的日志消息写入成功承诺之外,并且可能正在执行之前您的任务。请尝试以下操作:

$scope.users = []; 


$http.get("getjsondata").success(function (response) { 
    $scope.users = response; 
    console.log($scope.users); 
}); 

不要忘记承诺是异步的,因此将意味着它们会晚于无论是在执行console.log语句之后到来执行。

1

原因是console.log($scope.users);将在$http.get().success()执行之前调用;

$http.get()返回承诺。

可以调试此类似:

$http.get("getjsondata").success(function (response) { 
    console.log('i am after the promise return') 
    $scope.users = response; //ajax request to fetch data into $scope.data 
}); 
console.log('i get executed first'); 
console.log($scope.users); 
+0

感谢您以简单的方式理解此问题的方式。现在我明白了首先执行的语句的实际处理过程,以及为什么它实际上并没有打印由于异步调用而产生的值。 – manish