我在select元素中遇到默认值问题。 我有表格用于创建新项目并从表格更新。 这是我的代码:
控制器:
function MyController($scope){
$scope.data = {};
$scope.selectedItem = null; //selected row from table
this.edit = function(){
$scope.enableEditation = true; // displayed editation form
$scope.data = $scope.selectedItem
}
}
HTML:
<select required ng-model="data.ID" class="form-control">
<option ng-repeat="option in types" value="{{option.ID}}" ng-selected="option.ID == data.ID">{{option.ID}} - {{option.NAME}}</option>
</select>
默认值总是空的。在浏览器中生成的html是:
<select class="form-control ng-pristine ng-untouched ng-valid ng-not-empty ng-valid-required" required="" ng-model="data.ID">
<option selected="selected" value="? number:4 ?"></option>
<option class="ng-binding ng-scope" value="4" ng-repeat="option in types" ng-selected="option.ID == data.ID">4 - First</option>
<option class="ng-binding ng-scope" value="12" ng-repeat="option in types" ng-selected="option.ID == data.ID">12 - Last</option>
</select>
哪里有问题?谢谢你的建议。
答案 0 :(得分:1)
您只需将ng-selected="option.ID == data.ID"
替换为ng-selected="data.ID"
<select required ng-model="data.ID" class="form-control">
<option ng-repeat="option in types" value="{{option.ID}}" ng-selected="data.ID">{{option.ID}} - {{option.NAME}}</option>
</select>
答案 1 :(得分:1)
您的问题是您将值添加到选项中
"value={{option.id}}"
当您使用非字符串值时,这将始终导致类型冲突,因为这样做会将您的id转换为字符串,您最简单的解决方案是使用&#34; ng-value&#34;相反,并将其作为参考:
"ng-value="option.id"