0

I have a ng-options, an array and a default ng-options-model of 0, ie the first element in the array. Why is the first name in the array shown in the dropdown (it is only blank)?

See plunk.

I have this html:

<form>
  <select ng-options="index as contact.name for (index,contact) in contacts" ng-model="selectedContact"></select>
</form>
Selected contact array index (default 0): {{selectedContact}}

And this controller:

app.controller('MyCtrl', ['$scope', function ($scope) {
  $scope.contacts = [
    {email: "[email protected]", name: "Mini Me"},
    {email: "[email protected]", name: "Maxi You"}
  ];
  $scope.selectedContact = 0;
}]);

2 Answers 2

1

Your ng-options syntax is a bit wrong, you're using the syntax for iterating an objects properties, when you actually have an array of objects:

ng-options="contact as contact.name for contact in contacts"

And then you set the index of the array to select the first one:

$scope.selectedContact = $scope.contacts[0];
Sign up to request clarification or add additional context in comments.

2 Comments

The name is actually not unique. I have seen this way of iteration over an array for the reason of using the array index for the selected option...
@EricC - You should be using the above syntax, use $index to grab the index from the above syntax - then setting it as an actual number will work.
0

Ok, found the solution myself. ng-repeat has the index as a string (so selectedContact is a string), but my controller was using a number. When I change my controller to:

$scope.selectedContact = "0";

Then it worked perfectly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.