2016-07-26 107 views
1

我很努力把它變成ng選項。它甚至有可能嗎?什麼是角度ng選項相當於這個選擇?

<select ng-model="detail_type_id"> 
    <optgroup ng-repeat="type in data.detailTypes" label="{{type.name}}"> 
     <option ng-repeat="t in type.children" value="{{t.id}}">{{t.name}}</option> 
    </optgroup> 
</select> 

DetailTypes看起來是這樣的:需要選擇

[ 
{"id":7, 
    "parent_id":null, 
    "name":"Contact", 
    "children":[ 
    {"id":8, 
     "parent_id":7, 
     "name":"Address", 
     "children":[] 
    }, 
    {"id":12, 
     "parent_id":7, 
     "name":"Something else", 
     "children":[] 
    } 
    ]}, 
{"id":16, 
    "parent_id":null, 
    "name":"Other", 
    "children":[ 
    {"id":10, 
     "parent_id":16, 
     "name":"Remarks", 
     "children":[]} 
    ] 
} 
] 

子ID。嵌套不能更深。

回答

2

ngOptions指令不適用於多維對象。所以你需要壓扁你的數組來使用它。

我寫了一個過濾器:

app.filter('flatten' , function(){ 
    return function(array){ 
    return array.reduce(function(flatten, group){ 
     group.children.forEach(function(child){ 
     child.groupName = group.name; 
     flatten.push(child) 
     }) 
     return flatten; 
    },[]); 
    } 
}) 

和HTML部分會是這樣:

<select ng-model="detail_type_id" 
     ng-options="item.id as item.name 
        group by item.groupName for item 
        in data.detailTypes | flatten track by item.id"> 
</select> 

Plunker(版本#1過濾器): https://plnkr.co/edit/dxi7j8oxInv2VRJ1aL7F

我也修改你的對象是這樣的:

[{ 
    "id": 7, 
    "parent_id": null, 
    "name": "Contact", 
    "children": [{ 
    "id": 8, 
    "parent_id": 7, 
    "name": "Address", 
    "children": [] 
    }, { 
    "id": 12, 
    "parent_id": 7, 
    "name": "Something else", 
    "children": [] 
    }] 
}, { 
    "id": 16, 
    "parent_id": null, 
    "name": "Other", 
    "children": [{ 
    "id": 10, 
    "parent_id": 16, 
    "name": "Remarks", 
    "children": [] 
    }] 
}] 

編輯:

建議之後我寫另一個版本沒有過濾器,但平坦化控制器內的陣列。

追加控制器JS:

$scope.flattenDetailTypes = flattenDetailTypes($scope.data.detailTypes); 

    function flattenDetailTypes(array){ 
    return array.reduce(function(flatten, group){ 
     group.children.forEach(function(child){ 
     child.groupName = group.name; 
     flatten.push(child) 
     }) 
     return flatten; 
    },[]); 
    } 

標記:

<select ng-model="detail_type_id" 
     ng-options="item.id as item.name group by item.groupName for item in flattenDetailTypes track by item.id"></select> 

Plunker(版本#2不帶過濾器): https://plnkr.co/edit/D4APZ6

+0

對象有點大和翻譯,所以可能有錯誤。問題是你可以寫來實現相同的功能嗎? – icebreaker

+0

噢,我知道了。我會試一試。 –

+1

不錯的解決方案,但作爲一種改進,我建議你在控制器中做一次而不是做一個過濾器。 – developer033