pro.mean pro.mean - 3 months ago 15
AngularJS Question

ng-options selected data return object

I have a array of object

{ id:x, name: 's' }
and using ng-options to create drop down with default selected data. This is working fine so far.

Now when I select one of the option and see the selected data, it return complete object but i need only name field as well as default value must be selected on load.

// in controller
vm.teams = [
{
id: 1,
name:'First'
},
{
id: 2,
name:'Second'
},
{
id: 3,
name:'Third'
}
];

vm.teamFormData = {
team: ''
};

vm.getTeam = function(formData) {
$log.debug(formData); << here I get object
}

// in View
<select ng-init="vm.teamFormData.team = vm.teams[0]"
ng-model="vm.teamFormData.team"
ng-options="t.name for t in vm.teams track by t.id" >
</select>


Here is my working plunker

Answer

Your ngOptions syntax is slightly off - it's value as text for item in array

ng-options="t.name as t.name for t in vm.teams track by t.id"

And your ngInit then becomes

ng-init="vm.teamFormData.team = vm.teams[0].name"

Side note - you probably don't want ngInit - there's no real use case in your above example for it. Instead, just set the property in the controller.

See plunkr: https://plnkr.co/edit/7SGIdtfjucMnMqiEa7JY?p=preview