Reputation: 1683
I have an AngularJS page for editing surgeries, but I can't get any of the <select>'s to show the current value. All the other fields in the form show their current values so I'm not sure what I'm doing wrong.
I have a factory set up with ngResource, this is in my controller.
// Supporting Data
SurgeryData.get({'accessToken':$rootScope.accessToken})
.$promise.then(function(response){
$scope.surgeryData = response.surgeryData;
});
// Surgery Data
SurgeryServices.get({'surgeryId':$stateParams.surgeryId,'accessToken':$rootScope.accessToken})
.$promise.then(function(response){
$scope.surgeryDetails = response;
$scope.formData.surgeryId = $scope.surgeryDetails.surgery.id;
...
$scope.formData.surgeryStatus = $scope.surgeryDetails.surgery_status;
...
$log.log( angular.toJson( $scope.formData.surgeryStatus ) );
$log.log( angular.toJson( $scope.surgeryData.surgery_status ) );
});
This is the HTML for Surgery Status
<select class="form-control" ng-model="formData.surgeryStatus" ng-options="status.name for status in surgeryData.surgery_status"></select>
and this is what I get in the console from my 2 $logs
$scope.formData.surgeryStatus
{"id":16,"name":"Ready For Pick-Up"}
$scope.surgeryData.surgery_status
[{"id":13,"name":"Inventory Not On Site"},{"id":14,"name":"Inventory On Site"},{"id":16,"name":"Ready For Pick-Up"},{"id":15,"name":"Sterilized For Surgery"}]
The <select>'s in the form have all the options but (for this example) Ready for Pick-Up is not selected and I have an empty ? option added to the select
<select class="form-control ng-pristine ng-valid" ng-model="formData.surgeryStatus" ng-options="status.name for status in surgeryData.surgery_status">
<option value="?"></option>
<option value="0">Inventory Not On Site</option>
<option value="1">Inventory On Site</option>
<option value="2">Ready For Pick-Up</option>
<option value="3">Sterilized For Surgery</option>
</select>
Upvotes: 0
Views: 7175
Reputation: 1147
ng-init should be the way to go.
View:
<select class="form-control ng-pristine ng-valid" ng-init="formData.surgeryStatus = selected" ng-model="formData.surgeryStatus" ng-options="status.name for status in surgeryData.surgery_status track by status.id">
<option value="?"></option>
<option value="0">Inventory Not On Site</option>
<option value="1">Inventory On Site</option>
<option value="2">Ready For Pick-Up</option>
<option value="3">Sterilized For Surgery</option>
</select>
Viewmodel:
$scope.selected = $scope.surgeryDetails.surgery_id;
ng-init will find the matching value from your options and select it when loading. Be sure to set your ng-model equal to whatever value you want selected, which looks like your Id in this case?
Upvotes: 2