0

ユーザーが果物の名前を入力できるフォームを含むディレクティブがあるとします。

  1. FruitFindController があります。ユーザーは果物の名前「Apple」を入力し、コントローラーに送信するボタンをクリックします。
  2. コントローラーはサービス「GetFruitInfo(fruit)」を呼び出し、パラメーターとして「Apple」を渡します。
  3. 情報を受信したら、メソッド「addToListAndDoStuff()」を呼び出して、フルーツ情報をリストに追加する必要があります。

私の問題は、私の FruitFindController にあります (fruitFinder がサービスであると仮定します)...

 $scope.GetFruitInfo = function() {
                $scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField);
                // should alert "Found Fruit" and call addToListAndDoStuff() method to add the foundFruit information to the list managed by another directive, "FruitList".
            }

以下のコードを実行して警告ボックスをポップアップする前に、情報が $scope.foundFruit に保存されるのを待つ最善の方法は何ですか?

4

1 に答える 1

0

最善の方法は、promise を使用することです。fruitFinder サービスでは、GetFruitInfo メソッドは次のようになります。

function GetFruitInfo(fruit) {
  var delay = $q.defer();
  $http({method: 'GET', url: 'http://myapi.com/getFruitInfo?fruit=' + fruit}).
    success(function(data, status, headers, config) {   
      delay.resolve(data);
    }).
    error(function(data, status, headers, config) {
      delay.reject(data);
    });
  return delay.promise;
}

このメソッドは、次のように .then() メソッドを使用してコントローラーで解決されるまで待機できる promise オブジェクトを返します。

 $scope.GetFruitInfo = function() {
   $scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField).then(function(response) {
      alert('Found Fruit');
      addToListAndDoStuff(response);
    });
 }
于 2013-10-25T08:54:25.327 に答える