ng-options (key, values) in object [duplicate]

99封情书 提交于 2019-12-24 22:41:22

问题


I want to know how to use ng-options render a select Element works.

    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>

use ng-options how to make it work?


回答1:


Here is working code:

<!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>



回答2:


First you need to change your object structure something like

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'}
]

And use in HTML to bind this object to select with ng-options

<select ng-model="sel" ng-options="t.code as t.name group by t.group for t in data">


来源:https://stackoverflow.com/questions/50483263/ng-options-key-values-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!