Search code examples
javascriptangularjsangularjs-ng-options

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 = 1655153520848838061@groups.go.to

<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; //'1655153520848838061@groups.go.to'

   MyCtrl.userGroups = success.groups;

});

success.groups:

[
      {
        "groupJID": "11110567@groups.go.to",

        "profile": {
          "name": "Flock Desktop Dev - QA issues",
          "description": "QA/Dev Channel"
        }
      },
      {
        "groupJID": "1655153520848838061@groups.go.to",

        "profile": {
          "name": "Some group name",
          "description": "awesome Channel"
        }
      }
      {
        "groupJID": "1111067890@groups.go.to",

        "profile": {
          "name": "Flock Desktop 1",
          "description": "QA/Dev Channel"
        }
      },
      {
        "groupJID": "1111045678@groups.go.to",

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

Solution

  • 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