Angular select and ng-options
Asked Answered
P

2

8

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": ""
      }
    ]
  }
}
Pulque answered 14/12, 2015 at 16:14 Comment(1)
You sure you're updating to "300" and not 300?Universally
C
7

Remove track by.

From the Docs:

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

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". 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>
Convoke answered 14/12, 2015 at 16:21 Comment(2)
Not sure what exactly is going on, but removing the track by is working.Pulque
@Pulque I had this problem a lot when I started. reading the docs always help (most of angular methods are well documented...). Look at the edit, there is a defined line of what works and what doesnt.Convoke
M
2

According to the docs here: 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.

Monsour answered 14/12, 2015 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.