Angular select 和 ng 选项

Angular select and ng-options

我有这个angularselect:

<select ng-model='obj.status' ng-options='status.code as (status.code + " " + status.phrase) for status in status_codes.data track by status.code'>`

我的$scope.status_codes是这样的:

data: [
{
       "code":"100",
       "phrase":"...",
       "spec_title":"RFC7231#6.2",
       "spec_href":"http://tools.ietf.org/html/rfc7231#section-6.2"
}
...
]

我的 $scope.obj.status 更新为“300”或“100”或任何我更改 select 时的内容,但 select 显示始终为空白。因此,模型更新为 select 输入的 selected 值,但输入不显示当前 selected 值,它显示空白项。

如果我将 ng-options 更改为 ng-options='status as (status.code ...' 它会起作用,但我只想在我的模型中使用 status.code,而不是整个状态数组。给出了什么?

我的 HTML 中有 {{obj | json }},上面写着:

obj = {
  "name": "",
  "description": "",
  "payload": "",
  "status": "200",
  "responseHeaders": {
    "entry": [
      {
        "key": "",
        "value": ""
      },
      {
        "key": "",
        "value": ""
      }
    ]
  }
}

删除曲目。

来自Docs

Be careful when using select as and track by in the same expression.

我最好的猜测是 as 使用正常值,如“300”,但 track by 使用的是键入值,如 "int:300"。删除一个或另一个应该可以,最好是 track by.

他们以此为例:

This will work:

<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>

but this will not work:

<select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>

根据此处的文档:https://docs.angularjs.org/api/ng/directive/ngOptions:

select as label for value in array

因此在您的示例中这应该有效(您将获得代码值作为模型中的 select 值):

status.code as (status.code + " " + status.phrase) for status in status_codes.data

track by 当您将对象作为模型中的值、对象数组作为选项并且您希望将当前模型值与数组中的对象之一匹配时,应使用