Shamoon
Shamoon

Reputation: 43609

ng-model isn't updating when I change a select option

I have a select box with some ng-options, but it's not updating the ng-model when I select an option. I have a fiddle up at http://jsfiddle.net/32tntojs/ to view the source.

My HTML is

<div ng-controller="MyCtrl">
PARENTID: {{ parent_id }}
<select  ng-model="parent_id" ng-options="project.id as project.groupingName for project in projects track by $index"></select>
</div>

and when I select something, the parent_id doesn't update. What am I doing wrong?

Upvotes: 0

Views: 3244

Answers (3)

Aks1357
Aks1357

Reputation: 1072

Updated Fiddle : https://jsfiddle.net/32tntojs/3/

Your projects array of objects does not contain id so replaced it with gid

HTML :

<select ng-model="parent_id" ng-options="project.gid as project.groupingName for project in projects"></select>

Another mistake: as shouldn't be used with track by

Refer AngularJs Docs - https://docs.angularjs.org/api/ng/directive/ngOptions

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

Upvotes: 1

MarcoS
MarcoS

Reputation: 17721

You can't use $index in ng-options (as @plong0 points out).
This does work:

<div ng-controller="MyCtrl">
  PARENTID: {{ parent_id }}
  <select  ng-model="parent_id" ng-options="project.id as project.groupingName for project in projects track by $index"></select>
</div>

See updated fiddle.

Upvotes: 0

plong0
plong0

Reputation: 2188

It looks like your project objects do not have an id property. When I inspect the select element, all the option values are undefined.

The ng-option syntax looks fine and the ng-model does in fact update when I change it to:

<select  ng-model="parent_id" ng-options="project.gid as project.groupingName for project in projects track by $index"></select>

Upvotes: 3

Related Questions