2013-10-25 24 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并传入水果 –

相关问题