2016-08-19 42 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我想的對象。