我的 json 在 Angular 选择标签中绑定(bind)时遇到问题。
JSON:
{
"List": [
{
"service": [
"one"
],
"id": [
1
]
},
{
"service": [
"two"
],
"id": [
2
]
}
]
}
这里我需要在 select 标签中绑定(bind)服务属性。我正在获取对象数组。
如有任何帮助,我们将不胜感激。
谢谢
最佳答案
您得到一个数组,因为主列表中的每个项目都有一个 service
属性(property)和id
属性作为数组,因此为了填充选项列表,您需要使用以下内容:
ng-options="item.id[0] as item.service[0] for item in items.List"
我使用 $scope.items
将项目列表保存在 Controller 中我正在使用 ... in items.List
引用它在ngOptions
指令。
每个<option>
的值和 <select>
中的标题/标签使用 item.id[0] as item.service[0] for item
设置元素- 它选择每个 service
中的第一个元素和 id
每个选项的数组。
这是一个工作示例:
angular.module('app', []).controller('ctrl', function($scope) {
$scope.items = {"List": [
{
"service": [
"one"
],
"id": [
1
]
},
{
"service": [
"two"
],
"id": [
2
]
}
]};
$scope.selectionChanged = function(value) {
console.log(value);
};
// You can also define a pre-selected option by uncommenting the following line
// $scope.selected = 2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select ng-options="item.id[0] as item.service[0] for item in items.List" ng-model="selected" ng-change="selectionChanged(selected)"></select>
<div ng-if="selected">
Selected: <pre ng-bind="selected"></pre>
</div>
</div>
关于javascript - 如何为对象数组提供 ng-options?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55183059/