javascript AngularJS Select 元素设置选中索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26217067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:41:06  来源:igfitidea点击:

AngularJS Select element set the selected index

javascripthtmlangularjsdefaultselectedindex

提问by ErikBrandsma

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

所以我使用 angular,这是我选择的 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

结果:三个选项:一个空白(默认选中),然后是我在 html 中所做的两个选项

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

我勒个去?为什么当我打开视图“另一个选项”时不是默认值

回答by Nano

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

首先,请务必查看官方文档。AngularJs 有据可查。

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

其次,不要使用document.getElementById ("date") selectedIndex = "0"- 那是 javascript。当 Angular 函数可用时,避免使用纯 Javascript。

Documentation:

文档:

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

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

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

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