STEEL
STEEL

Reputation: 10067

ng-options selected not working with object as model [Angular 1.5]

Below code and everything loads fine, except it doesn't select the default option.

Also, one of the dropdown items value for option.groupJID does matches with MyCtrl.groupJID = [email protected]

<select id="groups-list2" ng-model="MyCtrl.groupJID" 
 ng-options="option.groupJID as option.profile.name for option in MyCtrl.userGroups track by option.groupJID">
</select>

Please review

ng-options enter image description here

Function:

SomeNetworkCall.then(function(success){
   MyCtrl.groupJID = success.peer; //'[email protected]'

   MyCtrl.userGroups = success.groups;

});

success.groups:

[
      {
        "groupJID": "[email protected]",

        "profile": {
          "name": "Flock Desktop Dev - QA issues",
          "description": "QA/Dev Channel"
        }
      },
      {
        "groupJID": "[email protected]",

        "profile": {
          "name": "Some group name",
          "description": "awesome Channel"
        }
      }
      {
        "groupJID": "[email protected]",

        "profile": {
          "name": "Flock Desktop 1",
          "description": "QA/Dev Channel"
        }
      },
      {
        "groupJID": "[email protected]",

        "profile": {
          "name": "Flock Desktop 2",
          "description": "QA/Dev Channel"
        }
      }
]

Upvotes: 0

Views: 772

Answers (1)

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16811

Taken from the docs

Be careful when using select as and track by in the same expression.

The value you specify in the Select As will be used as the option value but when you add a Track By expression the value which will be tracked is the Select as value and not the object. In your case the ngModel value is option.groupJID and the track by expression evaluates to option.groupJID.groupJID which is undefined.

To make it work, you could remove the Track by expression

<select id="groups-list2" ng-model="MyCtrl.groupJID" 
    ng-options="option.groupJID as option.profile.name for option in MyCtrl.userGroups">
</select>

Plunker here

Upvotes: 2

Related Questions