AngularJS Select element set the selected index
Asked Answered
A

1

6

So i'm using angular and this is my select html:

<select id="date" ng-model="selectedDay" ng-change="setDate()" >
    <option>another option</option>
    <option>an option</option>
</select>

this is in my controller:

$scope.selectedDay;
document.getElementById("date").selectedIndex = "0";

The result: Three options: one blank (which is default selected) and then the two options I made in html

What the hell? why isn't the default when i open the view "another option"

Afterbody answered 6/10, 2014 at 13:16 Comment(1)
Go with ngOptions when you use select in AngularJS docs.angularjs.org/api/ng/directive/selectAcuff
T
6

Firstly, always check the official documentation. AngularJs is well documented.

Secondly, do not use document.getElementById ("date") selectedIndex = "0" - that's javascript. Avoid using pure Javascript when an Angular function is available.

Documentation:

https://docs.angularjs.org/api/ng/directive/select

https://docs.angularjs.org/api/ng/directive/ngSelected

Treasurer answered 6/10, 2014 at 13:21 Comment(1)
Thank you! ng-selected="selectedOption" in controller: selectedOption = "another option" did the trick!Afterbody

© 2022 - 2024 — McMap. All rights reserved.