0

In my ionic project I have a <select> like so:

<select ng-model="user.bloodType" ng-options="x as x.description for x in formData.bloodTypes"></select>

So to clarify, user.bloodType is an object that looks like this:

{
  'id' : 1,
  'description' : 'O+'
}

formData.bloodTypes contains an array of the above depicted bloodType object. So here comes the problem - I know that user.bloodType is definitely one of the objects that is in formData.bloodTypes. How can I set the <select> to be pre-selected on whatever user.bloodType is?

  • Possible duplicate of [How to set a selected option of a dropdown list control using angular JS](http://stackoverflow.com/questions/17968760/how-to-set-a-selected-option-of-a-dropdown-list-control-using-angular-js) – M4N Jan 11 '16 at 13:16

1 Answers1

6

If you are not using reference equality to set ngModel to one of the options, you can rely on equality based on id by using a track by expression (the id should be unique per option):

ng-options="x as x.description for x in formData.bloodTypes track by x.id"

Then your ngModel user.bloodType can be initialized to a model whose reference does not necessarily match.

For example:

<select ng-model="selectedOption" ng-options="x 
          as x.description for x in bloodTypes track by x.id>

Controller:

app.controller('ctrl', function($scope) {
     $scope.bloodTypes = [
       {'id' : 1, 'description' : 'O+'},         
       {'id' : 2, 'description' : 'A'},
       {'id' : 3, 'description' : 'B'},
     ];

     // set initial selected option to blood type B
     $scope.selectedOption =  {'id' : 3, 'description' : 'B'};
});

Or if you want to preserve reference equality, you don't need track by:

app.controller('ctrl', function($scope) {
     $scope.bloodTypes = [
       {'id' : 1, 'description' : 'O+'},         
       {'id' : 2, 'description' : 'A'},
       {'id' : 3, 'description' : 'B'},
     ];

     // set initial selected option to blood type B
     $scope.selectedOption = $scope.bloodTypes[2];    
});
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • 1
    Could the above potentially be simplified then by doing this: // Just added ng-selected="user.bloodType" –  Jan 11 '16 at 13:41
  • 2
    No. It doesn't make much sense to mix the two. Use one or the other. ngModel is more useful - means less work in syncing the model – Michael Kang Jan 11 '16 at 13:44