javascript 选择框中的 ng-model 无法正常工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28497175/
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
ng-model in select box is not working correctly
提问by hard coder
I am using angular js to draw select boxes.
我正在使用 angular js 来绘制选择框。
<select ng-model="selected">
<option value="{{obj.id}}" ng-repeat="obj in values">{{obj.name}} </option>
</select>
selected id - {{selected}}
Here the default selected is not initialized according to value selected
.
这里默认选择的不是根据 value 初始化的selected
。
Have made a fiddlefor the problem.
已经取得了小提琴的问题。
回答by dfsq
You should use ngOptions
directive to render selectbox options:
您应该使用ngOptions
指令来呈现选择框选项:
<select ng-model="selected" ng-options="obj.id as obj.name for obj in values"></select>
Fixed demo:http://jsfiddle.net/qWzTb/1984/
固定演示:http : //jsfiddle.net/qWzTb/1984/
回答by Divya MV
case 2 is updated in this plunker
案例 2 在此 plunker 中更新
<div ng-repeat="arr in itr">
<select ng-model="arr.id"
ng-options="value.id as value.name for value in values">
</select>
回答by Siew Wing Fei
Just add ng-selected="selected == obj.id" in the option tag
只需在选项标签中添加 ng-selected="selected == obj.id"
<option value="{{obj.id}}" ng-repeat="obj in values" ng-selected="selected == obj.id" >
{{obj.name}}
</option>
回答by Saumyajit
Correct Way would be like :
正确的方式是这样的:
<select id="select-type-basic" [(ngModel)]="status">
<option *ngFor="let status_item of status_values">
{{status_item}}
</option>
</select>
Value Should be avoided inside option since that will set the default value of the 'Select field'. Default Selection should be binded with [(ngModel)] and Options should be declared likewise.
值应避免在选项内,因为这将设置“选择字段”的默认值。默认选择应与 [(ngModel)] 绑定,选项应同样声明。
status : any = "Completed";
status_values: any = ["In Progress", "Completed", "Closed"];
Declaration in .ts file
.ts 文件中的声明