9

I have this angular select:

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

My $scope.status_codes is like this:

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

My $scope.obj.status is updated to "300" or "100" or whatever as I change my select, but the select display is always blank. So, the model updates to the selected value of the select input but the input does not show the currently selected value, it shows a blank item.

If i change ng-options to be ng-options='status as (status.code ...' it works, but I only want status.code in my model, not the whole status array. What gives?

I have {{obj | json }} in my HTML and it reads:

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

2 回答 2

6

删除轨道。

文档

在同一表达式中使用 select as 和 track by 时要小心。

我最好的猜测是 as 使用正常值,如“300”,但 track by 使用的是类型值,如“int:300”。删除一个或另一个应该做到这一点,最好是跟踪。

他们以此为例:

这将起作用:

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

但这不起作用:

<select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
于 2015-12-14T16:21:49.097 回答
1

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

select as label for value in array

因此,在您的示例中,这应该可以工作(您将在模型中获得代码值作为选择值):

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

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

于 2015-12-14T16:40:10.610 回答