简体   繁体   English

角度选择和ng选项

[英]Angular select and ng-options

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: 我的$scope.status_codes是这样的:

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. 我的$scope.obj.status更新为“300”或“100”或更改我的选择,但选择显示始终为空白。 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? 如果我将ng-options更改为ng-options='status as (status.code ...'它可以工作,但我只想在我的模型中使用status.code,而不是整个状态数组。什么给出?

I have {{obj | json }} 我有{{obj | json }} {{obj | json }} in my HTML and it reads: {{obj | json }}在我的HTML中,它显示为:

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

Remove track by. 删除曲目。

From the Docs : 来自Docs

Be careful when using select as and track by in the same expression. 在同一表达式中使用select as和track by时要小心。

My best guess is that the as uses a normal value, like "300", but the track by is using a typed value, like "int:300". 我最好的猜测是as使用正常值,如“300”,但track by使用的是类型值,如“int:300”。 Removing one or the other should do it, preferably the track by. 删除一个或另一个应该这样做,最好是轨道。

They are giving this as an example: 他们以此为例:

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>

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

select as label for value in array

So in your example this should work (you will get code value as select value in model): 所以在你的例子中这应该有用(你将获得代码值作为模型中的选择值):

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

track by should be used when you have object as value in model, array of objects for options and you want to match current model value to one of objects in array. 当您将对象作为模型中的值,选项的对象数组以及您希望将当前模型值与数组中的某个对象匹配时track by应使用track by

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

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