Select not selecting when binding with ng-model and ng-options

Naner picture Naner · Mar 5, 2015 · Viewed 9.7k times · Source

Here's my select:

<select class="form-control" ng-options="assistanceType as assistanceType.name for assistanceType in assistanceTypes" ng-model="selectedRecord.assistanceType"></select>

Here's what I'm using to load the Assistance Types:

$scope.getAssistanceTypes = function () {
    $http.get('/api/assistanceType/getAll').
    success(function (data, status, headers, config) {
        $scope.assistanceTypes = data;
    }).
    error(function (data, status, headers, config) {
        alert(data.ExceptionMessage);
    });
}

Here's the result:

    [
  {
    "assistanceTypeId": 1,
    "name": "Essay"
  },
  {
    "assistanceTypeId": 2,
    "name": "Resume"
  },
  {
    "assistanceTypeId": 3,
    "name": "Test"
  }
]

Everything works fine and I can see the model being updated as I change options.

But when I load the record ($scope.selectedRecord), the selected option does not reflect the assistanceType object!

Here's the "selectedRecord":

{
  "recordId": 1,
  "student": {
    "id": "xxx",
    "firstName": "xxx",
    "lastName": "xxx"
  },
  "createDate": "2015-03-04T15:35:40",
  "closeDate": "2015-03-04T15:35:40",
  "checkInDate": "2015-03-04T15:35:40",
  "checkOutDate": "2015-03-04T15:35:40",
  "consultant": {
    "id": "xxx",
    "firstName": "xxx",
    "lastName": "xxx"
  },
  "assistanceType": {
    "assistanceTypeId": 1,
    "name": "Essay"
  },
  "course": {
    "course": "xxx",
    "name": "xxx",
    "teacher": {
      "id": "xxx",
      "firstName": "xxx",
      "lastName": "xxx"
    }
  },
  "format": null,
  "classStanding": null,
  "comment": "Nothing here!"
}

I'm new to AngularJS and I could very well be missing something here. But it looks like to me that at the moment I load the main record, the select should populate with the object in selectedRecord.assistanceType.

Any suggestions?

Thank you!

Answer

HankScorpio picture HankScorpio · Mar 5, 2015

The issue is that the "assistanceType" object in selectedRecord isn't the exact same instance of its equivalent in the assistanceTypes array. Try this:

<select class="form-control" ng-options="assistanceType as assistanceType.name for assistanceType in assistanceTypes track by assistanceType.name" ng-model="selectedRecord.assistanceType"></select>

Note that I added "track by assistanceType.name" so that it will compare them by name instead of the object's $$hashkey.