2017-03-02 4 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しています。これは、AJAXリクエストで非同期性によるものである(と仮定すると、データがバックエンドから正しく戻っている)

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) 

はコールバックでconsole.logの行を追加し、あなたのユーザーが表示されます - あなたは待つ必要がありますデータを使用するために要求が返されるまで

+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

関連する問題