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.

3
  • 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: plnkr.co/edit/b4ddyA5Q4jGNcJI1d8eW?p=preview Commented Mar 1, 2016 at 21:14
  • yeah, I tried, I got nothing... Commented Mar 1, 2016 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. Commented Mar 1, 2016 at 23:07

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.