JPS
JPS

Reputation: 2760

Dropdown is not selected by default when using object as model

I am using an javascript object as model for select menu, and ng-options also have object as the value property. I want the select menu to be pre-selected based on the model value. My html code,

<!DOCTYPE html>
<html>

  <head>
    <script src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3" data-require="angular.js@*"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body data-ng-app="myApp" data-ng-controller="MyCtrl as vm">
    <select data-ng-model="vm.model" data-ng-options="option as option.studentName for option in vm.options"></select>

    <br>
    <div>Model : {{vm.model}}</div>
    <br>
    <div>Options :<br>[ <div data-ng-repeat='option in vm.options'>{{option}}</div></div>
    ]
  </body>

</html>

Script,

// Code goes here
angular.module('myApp',[]);

angular.module('myApp').
controller('MyCtrl',MyCtrl);

function MyCtrl(){
  var vm = this;

  vm.model = {studentId:1,studentName:'Dheepan'};

  vm.options = [{studentId:1,studentName:'Dheepan'},
                {studentId:2,studentName:'Raju'}
               ];


}

Plunker here. I can understand that since ng-model and option are having different reference, it is not getting selected by default. Is there any way to do it?

Upvotes: 0

Views: 240

Answers (2)

Joao Polo
Joao Polo

Reputation: 2163

You can to use track by to define with field will be finded:

<select data-ng-model="vm.model" 
    data-ng-options="option as option.studentName for option in vm.options track by option.id"></select>

(your updated jsfiddle: http://embed.plnkr.co/6zNpJA4AsY50bpOQwnLl/preview)

Upvotes: 2

gaurav bhavsar
gaurav bhavsar

Reputation: 2043

You have to use option.studentId as option.studentName to bind studentId for selected studentName.

here is updated plunker

Try this :

<select data-ng-model="vm.model" data-ng-change="vm.changeStudent(vm.model)" data-ng-options="option.studentId as option.studentName for option in vm.options"></select>

I added ng-change to bind value and display on page.

Upvotes: 1

Related Questions