Lekhnath
Lekhnath

Reputation: 4625

selection not reflecting in select input with ngOptions

Angular is not able to reflect selected option in select input. Below is my complete code. Hospital One should have been selected, but not happening, what could be the reason ?

I've also put the same code snippet in JsBin also.

angular.module('testApp', [
  
])

.controller('AppController', function(){
  
  var vm = this;
  
  //
  vm.schedule = {
    date : "2015-5-25", 
    organization : {
      "_id":"55df26cf756549c15b5fbcd2",
      "name":"Hospital One",
      "kind":"HOSPITAL",
      "email":"[email protected]"
    }
  };
  
  //
  vm.user = { 
    name : "Some user name",
    affiliates : [
    {
        "_id":"55df26ea756549c15b5fbcd5",
        "createdOn":"2015-08-27T15:04:10.376Z",
        "organization":{
            "_id":"55df26cf756549c15b5fbcd2",
            "kind":"HOSPITAL",
            "name":"Hospital One",
            "email":"[email protected]"
            
        }
    },
    {
        "_id":"55df26ea756549c15b5fbcd4",
        "createdOn":"2015-08-27T15:04:10.375Z",
        "organization":{
            "_id":"55dbfd280713a3aa0d85158a",
            "kind":"CLINIC",
            "name":"Some Clinic",
            "email":"[email protected]"
            
        }
    }
]
  };
  
})

;
<!DOCTYPE html>
<html ng-app="testApp">
  <head>
    <title>Test</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>

  </head>

  <body ng-controller="AppController as vm">
    <h3>Selected Is : </h3>
    <pre>{{ vm.schedule.organization | json }}</pre>
    
    <h3>But selection is not reflecting in select</h3>
    <select ng-model="vm.schedule.organization" ng-options="affiliate.organization as affiliate.organization.name for affiliate in vm.user.affiliates | orderBy : 'organization.name' track by affiliate.organization._id">
      <option value="">-- Choose Organization --</option>
    </select>
  </body>
</html>

Upvotes: 2

Views: 72

Answers (1)

Daniel
Daniel

Reputation: 6491

From ngOptions docs:

select as and track by:

Do not use select as and track by in the same expression. They are not designed to work together.

Just remove the 'track by' and it'll work fine.

<select ng-model="vm.schedule.organization" ng-options="affiliate.organization as affiliate.organization.name for affiliate in vm.user.affiliates | orderBy : 'organization.name'">

working bin

-----EDIT------

Your options and your selected value are two different objects at first, therefore you'll always see the <-- Choose Organization --> option as selected before changing the select.

In order to solve that you need to bind the selected to be one of the options.

here's a working bin that solves that issue as well

Upvotes: 1

Related Questions