So I understand you want to start <select>
with a predefined value.
For this you can use ng-init
in the tag, only you can not only use the value of id
, or set the whole object, you need to find the index in the list that you used in ng-options
so the angular scope will make the "reference" correct. I've created an executable example to make it easier, but I've used a few different names of yours, but I think you can get an idea. Any questions just call.
-
The first problem in the second example you posted is in ng-model
you can not use the same name as the variable that received the list.
The second problem is in ng-options
the part that says you need to pass the name of the list and name of the variable that will represent an item in the item in lista
list, in your case, cadastro in cadastros
.
And third problem, the ng-model
of <select>
of a list of objects must be an object, so that angular can track and select the item you need.
I have edited the example below according to your second example.
angular
.module('myApp', [])
.controller('MyController', ['$scope', function($scope){
//Carrega o valor do input hidden
var obj = document.getElementById('myField').value;
//Altere esse array pela sua request
$scope.cadastros = [
{
cadastroNumber: "Maçã",
id: 10,
active: true
},
{
cadastroNumber: "Banana",
id: 12,
active: false
},
{
cadastroNumber: "Abacaxi",
id: 20,
active: true
},
{
cadastroNumber: "Melancia",
id: 13,
active: true
}
];
//Encontra o index do objeto que deve ser selecionado
$scope.cadastros.map(function(value, index){
if(value.id == obj){
$scope.indexDefault = index;
return;
}
})
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><bodyng-app="myApp">
<div ng-controller="MyController">
<input type="hidden" id="myField" name="myField" value="10" />
<select name="cadastro"
ng-options="
cadastro.cadastroNumber
for cadastro
in (cadastros|orderBy:'id' | filter:{active:true})
track by cadastro.id
"
ng-model="cadastroSelecionado"
ng-init="cadastroSelecionado=cadastros[indexDefault]"
id="cadastro">
</select>
</div>
</body>