3

PHP を使用してファクトリにデータを取得しています。これは、コントローラー内の成功コールバック関数に正しく表示されます。ただし、返されたデータを $scope.customers に割り当てた後でも、コールバックの後に console.log($scope.customers) を実行するとそこにはなく、ビューの [ng-repeat] もそれを取得しません。

返されたデータを $scope オブジェクトに割り当てている場合、データのスコープが成功コールバックのすぐ内側に制限される理由は何ですか?

var customersController = function($scope, customersFactory) {
  $scope.customers = [];
  customersFactory.getAllData()
    .success(function(customers) {
      $scope.customers = customers;
      console.log($scope.customers); // Object with correct data
    }); // No errors so only showing happy path
  console.log($scope.customers); // empty []
};
customersModule.controller('customersController', ['$scope', 'customersFactory', customersController]);
4

2 に答える 2

2

$http 関数は非同期で発生します。したがって、後に console.log を呼び出すと、customersFactory.getAllData常に空になります。

console.log($scope.customers); // Object with correct data

実際に起こっている

console.log($scope.customers); // empty []

成功のコールバックが正しく設定されていることを信頼でき$scope.customersます。サイトが後で発生することを理解する必要があるだけです。ビューをロードする前に scope.customers を設定する必要がある場合は、コントローラーで解決を使用することを検討してください。

于 2014-07-30T17:52:04.047 に答える
0

ではない

console.log($scope.customers); // empty []

前に実行

console.log($scope.customers); // Object with correct data

?

2 つ目は、success() コールバック内にあるため、最初のものよりもかなり遅く実行される可能性があります。

于 2014-07-30T17:50:02.793 に答える