我正在为我的select标签使用ng-options来为用户提供选择。一切都很完美,但在第一次选择一个选项后,默认的空白值就消失了。如果我想再次恢复到默认空白值怎么办?怎么办?如何保留该空白值?
以下是我的代码示例:
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Hello World!</h1>
<select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions">
</select>
</body>
</html>
<script>
var app = angular.module('app', []);
app.controller('myController', function($scope){
$scope.myOptions = [{
"value": null,
"label": null,
},{
"value": "First",
"label": "First",
},{
"value": "Second",
"label": "Second",
},{
"value": "Third",
"label": "Third",
}]
});
</script>
以下是plunker:http://plnkr.co/edit/5f17YxRfWFI4g40t3NEf?p=preview
答案 0 :(得分:2)
使用
<select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions">
<option value=""></option>
</select>
不要污染你的myOptions&#39;使用虚拟null对象,因为API不会返回相同的内容。您需要在表示层上处理它,如上所示。保存时,如果使用选择为空,则将其保存为空(如果处理正确)
你也可以拥有这样的东西
<option value="">---select---</option>
答案 1 :(得分:1)
只需在选项中添加空白选项,默认情况下选择空白,如:
git reset --hard 2315aed
这里我们添加空白选项
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-controller="myController">
<h1>Hello World!</h1>
<select ng-model="mySelection" name="" id="" ng-options="x.value as x.label for x in myOptions">
</select>
</body>
</html>
<script>
var app = angular.module('app', []);
app.controller('myController', function($scope){
$scope.mySelection = '';
$scope.myOptions = [{
"value": "",
"label": "",
},{
"value": "First",
"label": "First",
},{
"value": "Second",
"label": "Second",
},{
"value": "Third",
"label": "Third",
}]
});
</script>
并选择空选项{
"value": "",
"label": "",
}