1

I am having trouble with a <select> input and binding with AngluarJS. I've created a minimum working sample on Plunker: http://plnkr.co/edit/P4T25RoJrU4mvbBiUJ9S?p=preview.

The basic issue is as follows: the value in the dropdown is never pre-selected with the value from my model.

Additionally, in Angular 1.1.5, ng-options appears to not include a "label" on the generated <option> tags, so when you change selection the drop down control doesn't register any change.

Nate
  • 30,286
  • 23
  • 113
  • 184
  • If you remove the "track by option.id" from the ng-options, it should pre-select based on your model. I have the modified Plunker: http://plnkr.co/edit/b4ddyA5Q4jGNcJI1d8eW?p=preview – Vivek N Mar 01 '16 at 21:14
  • yeah, I tried, I got nothing... – TomSlick Mar 01 '16 at 21:30
  • @VivekN That seems to have fixed my problem. Thank you very much. Post that as an answer so I can accept it. – Nate Mar 01 '16 at 23:07

2 Answers2

1

Two issues:

  • Compare strings to strings
  • Be careful when using select as and track by in the same expression.

JS

angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ],
     //USE this
     selectedOption: '2'
     //NOT this
     //selectedOption: 2 //This sets the default value
     };
 }]);

HTML

<!-- remove 'track by option.id' -->

<select name="mySelect" id="mySelect"
    ng-options="option.id as option.name for option 
                in data.availableOptions track by option.id"
    ng-model="data.selectedOption">
</select>

From the Docs:

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

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>

-- AngularJS ng-options Directive API Reference

georgeawg
  • 48,608
  • 13
  • 72
  • 95
1

As requested by OP, adding the comment as the answer.

If you remove the "track by option.id" from the ng-options as following, it should pre-select based on your model.

<select name="mySelect" id="mySelect"
      ng-options="option.id as option.name for option in data.availableOptions"
      ng-model="data.selectedOption"></select>

Check out the modified Plunker: http://plnkr.co/edit/b4ddyA5Q4jGNcJI1d8eW?p=preview

Vivek N
  • 991
  • 12
  • 22