Enrique Martinez Enrique Martinez - 1 month ago 7
Javascript Question

Angular ng-options returning index instead of object value

Below is my ng options

<select ng-init="vm.tutors = vm.tutors || 0" ng-model="vm.tutors" ng-options="tutors.fullname as tutor for (tutor, fullname) in vm.tutors" class="form-control"></select>


and below is my object

vm.tutors
[Object { fullname="NAME"}, Object { fullname="NAME2"}}]

What is the reason I keep getting the index instead of the actual value

Answer

The reason you are getting the index is because you have some syntax/concept issues.

Your code looks like it needs some love so here is a decent example of the proper way to do this:

Controller:

$scope.vm.tutors = [{fullname: "NAME"}, {fullname: "NAME2"}];
$scope.vm.selectedTutor = ""; // you can assign a value if you would like to have an option preselected.

HTML: // in this example tutor.fullname is the Label and Value for the select option.

<select ng-model="vm.selectedTutor" ng-options="tutor.fullname for tutor in vm.tutors" ></select>

Now when you select an option the value will be assigned to $scope.vm.selectedTutor and it wont break your array.

Alternatively you can setup a key value pair relationship with your select options like so:

Controller:

$scope.vm.tutors = [{fullname: "NAME", id: "0"}, {fullname: "NAME2", id:"1"}];

HTML: // in this example tutor.id is the Value and tutor.fullname is the Label for the select option

<select ng-model="vm.selectedTutor" ng-options="tutor.id as tutor.fullname for tutor in vm.tutors" ></select>

I hope this helps you understand what is going on here a little better, also HERE is a link to the AngularJS documentation.