2016-08-19 38 views
0

我想调用角度/ ajax从API获取值,并希望设置我的结果期待结果格式。我试图用我的代码,但它调用的两倍,我不知道我在哪里弄错请建议使用angularjs得到结果的对象形式

$http.get('v1/res') 
     .success(function (data) { 

     $scope.results = []; 

     angular.forEach(data.data, function(value, key){ 
      $scope.results.push({id: value.id}); 
      $scope.results.push({text: value.name}); 

     }); 

     }); 

//期待的结果

$scope.results = [ 
    {id: 1, text: 'A'}, 
    {id: 2, text: 'B'}, 
    {id: 3, text: 'C'}, 
    {id: 4, text: 'D'}, 
    {id: 5, text: 'E'}, 
    {id: 6, text: 'F'}, 
    {id: 7, text: 'G'}, 
    {id: 8, text: 'H'}, 
    ]; 
+0

什么是你所得到的结果呢? –

+1

也许试着'$ scope.results.push({'id':value.id,'text':value.name});'? –

+0

你现在这样做的方式会将id和文本推送为两个不同的对象 –

回答

1

如果你从API调用得到的结果是相同的对象,只要你想,那么你可以简单地做如下

//assuming that data.data is an array of objects that you wish for 
$scope.result = [] 
angular.copy(data.data, $scope.result) 

否则

$scope.result = [] 
data.forEach(function(d){ 
    $scope.result.push({"id":d.id, "text":d.text}); 
}); 
0

是不是很够你让你的数据想从data.data,因为它是一个具有你想要的值的对象。

,你想获得期望的格式,它应该是objectidtext存储在$scope.results其属性,但在你的代码,它们被分别存储为单个对象的一个​​属性。所以,你的代码应该改变这样的:

angular.forEach(data.data, function(value, key){ 
    $scope.results.push({id: value.id, text: value.name}); 
}); 

{id: value.id, text: value.name}是要存储在您的$scope.results我想的对象。