Mark Sandman Mark Sandman - 1 year ago 49
Javascript Question

AngularJS: Trying to set seleted in ng-options and output value, not whole object

I have a problem with ng-options, I don't really understand them! However as I read the documentation I was wondering if you can help.

I have a simple object array in my controller like so...

$scope.childrenType = [
label: 'None',
value: -1
label: 'Son',
value: 0
label: 'Daughter',
value: 1
label: 'Step Son',
value: 2
label: 'Step Daughter',
value: 3

I use this to populate a select menu in my view...

<select data-ng-model="child.type"
data-ng-options="type.label for type in childrenType track by type.value"
What is selected: {{ child.type }}

The directive 'data-clean-up-select' just removed the empty option we get with
. Now I want to do two things, I want to pre-select the select default value (from data that comes from a service but for simplicity we will set it here like so)

$scope.child.type = 2;

Now the default value is not selected (I want Step Son to be selected in this example) and on change I only want the value to be the value, integer not the whole object of the

So when I change the menu I want the value to just be
, etc... and not

I have prepared a JSBin to demonstrate my problem...

Here is a JsBin:,js,output


You need to change your ng-option like this :

<select data-ng-model="child.type"
        data-ng-options="type.value as type.label for type in childrenType"

Before the as, you have the value store on your model. If you want just the value, type.value will do the trick. And because you save just the value on your ng-model. Your previous initialisation on Step brother will be fine too.

Moreover, in this situation you don't need to use track by. The "as part" of your options already do this job.