如何为对象数组提供ng-options?

3

我在Angular中使用select标签绑定JSON时遇到了问题。

JSON:

{
"List": [
    {
        "service": [
            "one"
        ],

        "id": [
            1
        ]
    },
    {
        "service": [
            "two"
        ],

        "id": [
           2
        ]
    }
    ]
}

我需要在select标签中绑定服务属性。我得到了对象数组。
任何帮助都将不胜感激。
谢谢
1个回答

1

您得到了一个数组,因为主列表中的每个项目都有一个service属性和id属性作为一个数组,所以为了填充选项列表,您需要使用以下内容:

ng-options="item.id[0] as item.service[0] for item in items.List"

我使用$scope.items在控制器中保存了项目列表,并在ngOptions指令中使用... in items.List进行引用。
每个<option>的值和<select>元素中的标题/标签是使用item.id[0] as item.service[0] for item设置的-它选择每个选项的serviceid数组中的第一个元素。
这是一个可行的例子:

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接