Select not selecting when binding with ng-model and ng-options
Asked Answered
H

2

5

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!

Hairball answered 4/3, 2015 at 23:31 Comment(0)
S
17

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.

Saiz answered 4/3, 2015 at 23:47 Comment(0)
R
1

Select element require name attribute to get model element select, in your case just add add name attribute. For example name="assistanceType". There is no need to add track by untill its require.

Rebozo answered 24/5, 2019 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.