2013-10-25 19 views
0

假設我有一個指令,其中包含一個用戶可以輸入水果名稱的表單。如何在angularjs中處理控制器中的數據?

  1. 我有一個FruitFindController。用戶輸入水果名稱「Apple」,點擊提交給控制器的按鈕。
  2. 控制器調用服務「GetFruitInfo(fruit)」並傳入「Apple」作爲參數。
  3. 一旦收到信息,它應該調用一個方法「addToListAndDoStuff()」,以便將fruitinfo添加到列表中。

我的問題是,在我的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下方彈出警告框的任何代碼?

+0

是您的fruitFinder返回一個承諾? – ivarni

+0

FruitFinder服務如何獲得水果信息? – callmekatootie

回答

0

最好的方法是使用一個承諾。在你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; 
} 

該方法返回一個承諾的對象,你可以等待它在你的控制器使用。那麼()方法,這樣解決..

$scope.GetFruitInfo = function() { 
    $scope.foundFruit = fruitFinder.GetFruitInfo($scope.fruitField).then(function(response) { 
     alert('Found Fruit'); 
     addToListAndDoStuff(response); 
    }); 
} 
+0

如果我需要提出100個水果請求100個水果和「addToListAdnDoStuff」,它有多複雜?這些承諾是否仍然相關,並且是處理這個問題的最佳方式? – Rolando

+0

承諾幾乎肯定是處理您從角度應用程序發送的任何http請求的最佳方式。如果你需要發送請求到不同的URL,你可以將整個url傳遞給GetFruitInfo(url),而不是硬編碼url並傳入水果 –

相關問題