2017-03-02 34 views
0

我想用我的控制器從工廠使用$ http諾言。下面的代碼工作,我可以通過調用{{users}}

工作廠查看該用戶在視圖中的變量:

.factory('bidsCreatedSimple', ['$http', function($http) { 
    // Expose public API first, use func notation 
     return { 
      getUsers: getUsers, 
     }; 

     function getUsers(){ 
      return $http.get('/bids.json'); 
     } 
}]) 

在控制器:

$scope.users = []; //visible in the view 

activate(); 

function activate(){ 
    bidsCreatedSimple.getUsers().then(function(users){ 
     $scope.users = users.data; 
    }); 
} 

console.log($scope.users); //returns a blank [] even though 
          //it renders with data in the view 

我如何使用$範圍。用戶變量在我的控制器?我需要將它的數據用於控制器中的其他對象。

回答

2

你的代碼很好。 $scope.users DOES會被填入數據,但您的console.log($scope.users)會在請求返回$http之前執行 - 因此您是console.logging您聲明在代碼頂部的空數組。

添加console.log線在回調,你會看到你的用戶(假設數據是從你的後端正確返回)

bidsCreatedSimple.getUsers().then(function(users){ 
     $scope.users = users.data; 
     // here $scope.users is filled with the .json data 
     console.log($scope.users) 
     // put here your code to manipulate users (or call a function that does that properly) 
    }); 
// here the $scope.users is undefined, because when this line executes, the request from get users hasn't returned yet (and the callback function hasn't executed either) 
console.log($scope.users) 

這是由於異步的Ajax請求 - 你需要等待數據,直到請求返回才能使用它。

+0

沒錯,但我在控制器中有一堆使用'$ scope.users'的對象。例如'$ scope.gridOptions.data'需要設置爲'$ scope.users',以便庫能夠渲染網格。我將如何將這些變量設置爲用戶數據? – HoosierCoder

+0

你使用angular-ui嗎?我沒有使用它,但你可能可以設置對$ scope.users的引用,然後使用一些刷新方法或類似的東西。像http://stackoverflow.com/questions/26634063/how-to-use-refresh-method-in-ui-grid –

+0

但是,我將如何實際使用控制器中的數據?我需要將它傳遞給一些服務,這將操縱它 – HoosierCoder