2014-05-15 43 views
2

我不知道如何通過這個JSON數據與AngularJS使用AngularJS陣列解析JSON文件

{  
    { 
     "1590": { 
     "id": "1590", 
     "id_site": "0", 
     "id_merk": "7", 
     "id_type": "209", 
     "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW" 
    }, 
    { 
     "1590": { 
     "id": "1590", 
     "id_site": "0", 
     "id_merk": "7", 
     "id_type": "209", 
     "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW" 
    } 
} 

幫助迭代這是我在我的角度應用程序現在:

服務

(function() { 

    var releasingService = function ($http) { 

     var brands = []; 
     $http.get('/releasing.json') 
      .then(function(results) { 
       brands = results; 

     }); 

     this.getBrands = function() { 
     return brands; 
     }; 

    }; 

    releasingService.$inject = ['$http']; 

    angular.module('releasingApp').service('releasingService', releasingService); 

}()); 

查看

<select data-ng-model="brands" data-ng-options="brand.Id for brand in brands"> 
    <option value="">-- Selecteer een merk --</option> 
</select> 

當前視圖不顯示任何結果。我不知道如何解決陣列中的不同對象。

任何幫助,將不勝感激。

+0

看起來像{{}}的有效json,你寫了什麼json看起來像正確嗎? – mpm

+0

是的,這實際上是當我從服務器請求它時JSON的外觀。所以我不能自己改變輸出。 –

回答

2

你不能迭代你的JSON,因爲它不是表示數組而是Object。

大括號,如:

[ 
    { 
    "1590": { 
     "id": "1590", 
     "id_site": "0", 
     "id_merk": "7", 
     "id_type": "209", 
     "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW" 
    } 
    }, 
    { 
    "1590": { 
     "id": "1590", 
     "id_site": "0", 
     "id_merk": "7", 
     "id_type": "209", 
     "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW" 
    } 
    } 
] 

第二個選項是key-value介紹:

{ 
    "1590": { 
    "id": "1590", 
    "id_site": "0", 
    "id_merk": "7", 
    "id_type": "209", 
    "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 147kW" 
    }, 
    "1591": { 
    "id": "1591", 
    "id_site": "0", 
    "id_merk": "7", 
    "id_type": "201", 
    "uitvoering": "Blue Lease Execut. HYbrid4 2.0 HDi 4D 142kW" 
    } 
} 

所以HTML應該是這樣的:

<select data-ng-model="selectedItem" 
     data-ng-options="key as value.uitvoering for (key , value) in brands"> 
    <option value="">-- Selecteer een merk --</option> 
</select> 

Demo in Fiddle

助手 你可以使用這個在線幫助:jsoneditoronline

1

我寫一個例子給你:plnkr

首先,你所提供的JSON是不是一個有效的JSON。根據結構,您可能必須更改ng-options中的表達式。然後,我建議您將$ http promise返回給控制器,並在執行ajax之後解析結果。最後,將結果呈現給select元素。我希望這能幫到您。如果您想了解更多選擇選項的詳細信息,您還可以查看api文檔ng on select