var data = {
china:[
{name:'shanghai',code:1},
{name:'zhejiang',code:2}
],
us:[
{name:'Alabama',code:3},
{name:'Alaska',code:4}
]
};
than,will render like this
<select>
<optgroup label="china">
<option value="1">shanghai</option>
<option value="2">zhejiang</option>
</optgroup>
<optgroup label="us">
<option value="3">Alabama</option>
<option value="4">Alaska</option>
</optgroup>
</select>
答案 0 :(得分:1)
这是工作代码:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select>
<optgroup label="{{key}}" ng-repeat="(key,value) in data">
<option value="{{val.code}}" ng-repeat="val in value" ng-selected="{{val.code==defaultValue}}">{{val.name}}</option>
</optgroup>
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.defaultValue = "4"; // Any default value you want here
$scope.data = {
china:[
{name:'shanghai',code:1},
{name:'zhejiang',code:2}
],
us:[
{name:'Alabama',code:3},
{name:'Alaska',code:4}
]
};
});
</script>
</body>
</html>
&#13;
答案 1 :(得分:0)
首先,您需要更改像
这样的对象结构const data = [
{name: 'shanghai', code: 1, group: 'china'},
{name: 'zhejiang', code: 2, group: 'china'},
{name: 'Alabama', code: 1, group: 'us'},
{name: 'Alaska', code: 2, group: 'us'}
]
并在HTML中使用绑定此对象以使用ng-options
进行选择<select ng-model="sel" ng-options="t.code as t.name group by t.group for t in data">