对象中的ng-options(键,值)

时间:2018-05-23 08:18:46

标签: angularjs ng-options

我想知道如何使用ng-options渲染选择元素。

    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>

使用ng-options如何使其工作?

2 个答案:

答案 0 :(得分:1)

这是工作代码:

&#13;
&#13;
<!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;
&#13;
&#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">