Robert Vliek
Robert Vliek

Reputation: 57

:AngularJS: ng-selected is not working with a true statement

I have a a select box like this:

    <select class="form-control"
            ng-model="contactName"
            ng-change="testFun(contactName)"
            ng-options="contact.Id as contact.Name + ' ' + contact.Surname for contact in company.items.contacts"
            ng-selected="$scope.contactId === contact.Id">
    </select>

Where $scope.contactId = 14151 and contact.Id = 14151

But the select box is still not selecting the right person and remains to show up blank.

I can't figure out what I am doing wrong here.

EDIT

<select class="form-control" 
        ng-model="contactName"
        ng-change="testFun(contactName)"
        ng-options="contact.Id as contact.Name + ' ' + contact.Surname + ' id:' + contact.Id for contact in company.items.contacts"
        ng-selected="contactId == contact.Id">
 </select>
 <pre>
    contactId: {{contactId}}
 </pre>

Which results in the following, which also confirms that the ID's are the same:
ContactId
Option with the same ID

The box is still coming up blank

Upvotes: 3

Views: 1242

Answers (2)

Abdullah Al Noman
Abdullah Al Noman

Reputation: 2878

Use ng-init this will work . You can not use $scope inside html . Removing the $scope would work .

<select class="form-control"
        ng-model="contactName"
        ng-change="testFun(contactName)"
        ng-options="contact.Id as contact.Name + ' ' + contact.Surname for contact in company.items.contacts"
        ng-init="contactName = contactId" >
</select>

ngSelected does not work with ngOptions you must use ng-init instead.

Upvotes: 1

bamtheboozle
bamtheboozle

Reputation: 6436

From the AngularJS docs:

Note: ngSelected does not interact with the select and ngModel directives, it only sets the selected attribute on the element. If you are using ngModel on the select, you should not use ngSelected on the options, as ngModel will set the select value and selected options.

That being said, you should use ng-init="contactName = contactId" as @Noman suggested, which initializes the contactName variabile with the contactId, selecting the correct option subsequently.

Upvotes: 2

Related Questions