javascript 将枚举值绑定到 ng-options angular js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27635219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:45:01  来源:igfitidea点击:

Bind enum values to ng-options angular js

javascriptangularjsselectng-optionsangularjs-ng-options

提问by forgottofly

The response JSON from a http GET method is as shown below

来自 http GET 方法的响应 JSON 如下所示

 [
    {
        "1": "Open"
    },
    {
        "2": "Expired"
    }
]

How to bind this data in a select drop down box in angular js. I tried with this option:

如何在 angular js 的选择下拉框中绑定这些数据。我试过这个选项:

<select class="form-control" ng-model="selected" ng-options="item for item in data"> 
<option value="">----Select----</option> 
</select>

But I'm getting [object,object] in the drop down list.

但是我在下拉列表中得到了 [object,object]。

回答by mcfedr

You could transform the json data into the format expected by ng-options simply using Array.reduce, along the lines of

您可以将 json 数据转换为 ng-options 期望的格式,只需使用Array.reduce, 沿着

$scope.options = data.reduce(function(memo, obj) {
    return angular.extend(memo, obj);
}, {});

<select ng-model="selected" ng-options="key as val for (key, val) in options"></select>

Full example here http://plnkr.co/edit/PV4BYrz0KBkIFPWVzVaT?p=preview

完整示例在这里http://plnkr.co/edit/PV4BYrz0KBkIFPWVzVaT?p=preview

回答by A.B

you need a key,valuein ng-repeat syntax as you have unknown or different keys

你需要一个key,valuein ng-repeat 语法,因为你有未知或不同的键

And you have to keep track of two repeats first for array and then for keys inside the objects

并且您必须首先跟踪数组的两次重复,然后跟踪对象内的键

<select class="form-control" ng-model="selected" > 
<option value="">----Select----</option> 
   <optgroup ng-repeat="v in values">

     <option ng-repeat='(key,value) in v' value="{{key}}">{{value}}</option>
   </optgroup>  
</select>

Demo

演示

value in option will be "open"or "expired" you can change it to keys "0" or "1" if you replace value={{value}}with value="{{key}}"

选项中的值将是 "open"或 " expired" 你可以将其更改为键 " 0" 或 " 1" 如果您替换value={{value}}value="{{key}}"

app = angular.module('test',[]);
app.controller('testctrl',function($scope){
$scope.values =[{"1": "Open" },{"2": "Expired" }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="testctrl" ng-app="test">
<span ng-if="selectedModel">{{selectedModel}}</span>
<select class="form-control"  ng-model="selectedModel"> 
<option>----Select----</option> 
   <optgroup ng-repeat="v in values">
     
     <option ng-repeat='(key,value) in v' value="{{value}}">{{value}}</option>
   </optgroup>  
</select>
  </div>