Nathan Kamenar
Nathan Kamenar

Reputation: 884

Angular default select option

I am having a problem getting my select to properly set the default option for my data. I am fetching data from a server through an Ajax call. I then want to be able to edit this data using a form. I want to point the select to use options set in a controller object but when you edit the select I want the model to point to the ajax data because that is what I write back to the server. As you can see in my plunkr each of the four items should have their select options filled in but instead all of the selects start empty.

In the official documentation for angular they say to do the following to set the default:

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'}
  ],
  selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  };
}]);

//Then in the HTML file:
<select name="mySelect" id="mySelect"
  ng-options="option.name for option in data.availableOptions track by option.id"
  ng-model="data.selectedOption"></select>

In my case the options aren't in the ajax data however, only the currently selected option. So I want to manage available options via a controller object but bind the select to the ajax data. Thanks.

https://plnkr.co/edit/Q16QLT?p=preview

Upvotes: 0

Views: 205

Answers (3)

Rahul Arora
Rahul Arora

Reputation: 4523

This will definately work:

Since your ng-model contains the full option object you need to bind it with the object in ng-options as well

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

Upvotes: 0

Rani Radcliff
Rani Radcliff

Reputation: 5074

Change your select to this:

<select ng-options="option.text as option.text for option in options" ng-model="item.select"></select>

Upvotes: 0

Aleksey L.
Aleksey L.

Reputation: 37918

You should define which property of "option" you want to bind to:

<select ng-options="option.value as option.text for option in options" ng-model="item.select"></select>

Working demo https://plnkr.co/edit/BezGaYjykfQrFQ9nZop2?p=preview

Upvotes: 1

Related Questions