2016-07-26 61 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