I am facing a frustrating issue with understanding how AngularJS
manages select option values and selections. I have a basic item that I pass to a modal window, which includes a template_id
. Additionally, I have a list of templates
with names and ids, and I want to create a select field where the option with the value matching the item's template_id is automatically selected:
<select name="templateId">
<option value="8000">name</option>
<option value="8001" selected>name 2</option>
</select>
To achieve this with AngularJS, I use the following code:
<select name="templateId"
ng-model="domain.templateId"
ng-options="t.template_id as t.name for t
in templates track by t.template_id">
<option value="">Choose template</option>
</select>
In the controller, I set the 'selected' value as follows:
Data.get('templates').then(function(result) {
$scope.templates = result;
});
$scope.domain = {
template_id: item.template_id,
templateId: { template_id: item.template_id }
};
While I can successfully send the template_id to the REST API, the response indicates:
template_id: 8000
However, there is a minor issue with the select element. Initially, the correct item is selected, but if I try to choose another option, it reverts back to the default 'Choose template' option, even though the actual selected item remains the one set in the controller. This behavior is not what I intend. Once this initial issue is bypassed, the select field functions correctly. How can I fix this inconsistency?