select 框中的 ng-model 无法正常工作
ng-model in select box is not working correctly
我正在使用 angular js 绘制 select 个框。
<select ng-model="selected">
<option value="{{obj.id}}" ng-repeat="obj in values">{{obj.name}} </option>
</select>
selected id - {{selected}}
这里默认selected没有根据值selected
初始化。
已针对该问题做出fiddle。
您应该使用 ngOptions
指令来呈现选择框选项:
<select ng-model="selected" ng-options="obj.id as obj.name for obj in values"></select>
案例 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>
只需在选项标签中添加 ng-selected="selected == obj.id"
<option value="{{obj.id}}" ng-repeat="obj in values" ng-selected="selected == obj.id" >
{{obj.name}}
</option>
正确的方式应该是:
<select id="select-type-basic" [(ngModel)]="status">
<option *ngFor="let status_item of status_values">
{{status_item}}
</option>
</select>
Value 应避免在选项内部,因为这将设置 'Select field' 的默认值。默认选择应与 [(ngModel)] 绑定,选项应同样声明。
status : any = "Completed";
status_values: any = ["In Progress", "Completed", "Closed"];
.ts 文件中的声明
我正在使用 angular js 绘制 select 个框。
<select ng-model="selected">
<option value="{{obj.id}}" ng-repeat="obj in values">{{obj.name}} </option>
</select>
selected id - {{selected}}
这里默认selected没有根据值selected
初始化。
已针对该问题做出fiddle。
您应该使用 ngOptions
指令来呈现选择框选项:
<select ng-model="selected" ng-options="obj.id as obj.name for obj in values"></select>
案例 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>
只需在选项标签中添加 ng-selected="selected == obj.id"
<option value="{{obj.id}}" ng-repeat="obj in values" ng-selected="selected == obj.id" >
{{obj.name}}
</option>
正确的方式应该是:
<select id="select-type-basic" [(ngModel)]="status">
<option *ngFor="let status_item of status_values">
{{status_item}}
</option>
</select>
Value 应避免在选项内部,因为这将设置 'Select field' 的默认值。默认选择应与 [(ngModel)] 绑定,选项应同样声明。
status : any = "Completed";
status_values: any = ["In Progress", "Completed", "Closed"];
.ts 文件中的声明