繁体   English   中英

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

[英]how to give ng-options for array of objects?

我在json中遇到问题,因为绑定在angular中的select标签中。

JSON:

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

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

        "id": [
           2
        ]
    }
    ]
}

在这里,我需要绑定select标签中的服务属性。 我正在获取一系列对象。

任何帮助,将不胜感激。

谢谢

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

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

我使用$scope.items保存了控制器中的项目列表,并使用ngOptions指令... in items.List中的... in items.List引用它。

每个<option>的值和<select>元素中的caption / label是使用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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM