2014-09-30 95 views
2

的REST API返回的restangular GET請求JSON對象和響應僅約在angularjs承諾的功能廣東話訪問restangular請求

Restangular.all('getUsers').getList().then(function(response) { 
    $scope.users = response; 
    angular.forEach($scope.users, function(value, key) { //This works 
     console.log(key + ': ' + value); 
    }); 
    }); 

    angular.forEach($scope.users, function(value, key) { //This does not work 
     console.log(key + ': ' + value); 
    }); 
+0

'的GetList()'是異步。回調之外的'forEach()'在getList()返回並填充'$ scope.users'之前運行。 – 2014-09-30 06:33:58

回答

3

閱讀(更多)內部觸及之外的範圍變量。

then()中的函數僅在REST請求返回響應後執行。

下面的代碼在請求發送完成後立即運行,但是在處理完響應之前。

你可以做

$scope.$watch("users", function() { 
    angular.forEach($scope.users, function(value, key) { //This does now work 
      console.log(key + ': ' + value); 
     }); 
}); 
+0

真的幫助,讓它工作..... – 2014-10-08 09:26:40

+0

在這種情況下,如果你將答案標記爲接受,那將是很好的。 – 2014-10-09 07:01:06