From what I understand you want to start the <select>
with a predefined value.
For this you can use the ng-init
on the tag, only that you cannot use only the value of the id
, or set the whole object, you need to find the index in the list you used in ng-options
so the angular scope will make the "reference" correct. I created an executable example to make it easier, but I used some different names than yours, but I think I can get an idea. Any doubt just call.
--
The first problem in the second example you posted is on ng-model
you cannot use the same name of 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 a list item item in lista
, in your case, cadastro in cadastros
.
And third problem, the ng-model
of <select>
of an object list needs to be an object, so that angular can trackear and select the item you need.
I 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>
<body ng-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>
You used the answer area to add clarifications or ask a question. Instead, it is better to include this content in the question itself. To do this, just click on the [Edit] link, which is just below the question. Thus, the content is all gathered in one place, and those who arrive here need not be looking for information in various responses and comments to understand the problem.
– user28595