我是在問幾乎一樣,你當堆棧溢出建議我看看你的問題相同的問題的過程。看起來我們從相同的source獲得了國家/地區列表。 我也不想改變結構。但在看到接受的答案後,我不想這樣破解它。所以相反,我寫了一個可重用的服務,它將變形任何類似的數據結構。
的服務
/*
* Morphs an array of a key/val pair to have the original key, be a value, and
* give new property names
*
* @method keyValMorph
* @param {array of objects} ex: [ {US:'United States'} ]
* @param {string} keyName - desired property name for the original key
* @param {string} valName - desired property name for the original value
* @return {array of objects} ex: [ {key: 'US', val: 'United States'} ]
*/
.factory('keyValMorph', function() {
return function (data, keyName, valName) {
var sort = [], keyName = keyName || 'key', valName = valName || 'val';
for (var i = 0; i < data.length; i++) {
var obj = {};
for (var key in data[i]) {
obj[keyName] = key;
obj[valName] = data[i][key];
sort.push(obj);
}
}
return sort;
};
})
控制器電話:
$scope.countriesSorted = keyValMorph($scope.countries, 'code', 'name');
這需要你的原始數據結構,並把它變成:
$scope.countriesSorted = [
{code:"US", name:"United States"},
{code:"CA", name:"Canada"},
{code:"AF", name:"Afghanistan"},
{code:"AL", name:"Albania"},
{code:"DZ", name:"Algeria"},
{code:"DS", name:"American Samoa"}
];
HTML
<select data-ng-model="selected" data-ng-options="country.code as country.name for country in countriesSorted ">
<option value="">[-- select --]</option>
</select>
也許最好寫一點來展開數據,並將其轉換爲更容易處理的對象數組http://stackoverflow.com/questions/8312459/iterate-through-object-properties可以在服務中完成檢索數據。 – shaunhusain