0
Hello, I have an array of objects that I am pulling from the database and playing in a Select HTML, only I am also passing another variable and would like to compare this variable with the values of the BD array and if they are equal set to Selected option. I’m using angular. Below is the code I’m using:
<div class="col-xs-12 input_formulario" ng-init="vm.tipoSeguro()">
<select name="setor_destino" required="" ng-model="user.tipoSeguro" >
<option value="">Nome do seguro</option>
<option ng-repeat="seguros in vm.mostraTipoSeguro track by seguros.id" value="{{seguros.nome}}">{{seguros.nome}}</option>
</select>
</div>
The ng-model I have in select is to send the selected value to the function in the controller that sends the form by email.
Follows HTML made with the answer Gabriel Câmara:
<select name="setor_destino" required="" ng-model="user.tipoSeguro" >
<option value="">Nome do seguro</option>
<option ng-repeat="seguros in vm.mostraTipoSeguro track by seguros.id" value="{{seguros.nome}}" ng-selected="seguros.id == vm.cookie">{{seguros.nome}}</option>
</select>
And my controller:
vm.tipoSeguro = function () {
SimulacaoService.listaTipoSeguro().then(function (response) {
if (response.data != 0) {
vm.mostraTipoSeguro = response.data;
vm.cookie = $.cookie("nome_seguro");
$.removeCookie("nome_seguro");
} else {
vm.mostraTipoSeguro = '';
}
}, function (error) {
console.error(error);
});
}
Try to foreach the controller and assemble a new list, you can create a new attribute
checked
in this new list, and everyone who is equal has this value true, and the rest has the value false– DiegoAugusto
Another repetition would cause performance problems, since the angular checks all variables in the $Digest cycle, imagine if the value of any of the elements within the structure
mostraTipoSeguro
If there was a change, this would cause all the Watchers to be activated in the next cycle and these would fire more Watchers until there were no more changes. Now within each cycle of that, there would be anotherforEach
being executed. For a small application maybe the cost is not high and almost not noticed, but in a large application would make a difference, especially in cell phones.– Gabriel Câmara