简体   繁体   中英

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

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM