2017-03-02 113 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