【问题标题】:How to add placeholder in ng-repeat dropdown input box?如何在 ng-repeat 下拉输入框中添加占位符?
【发布时间】:2018-01-03 06:03:56
【问题描述】:
我正在使用 ng-repeat 实现一个下拉菜单。我想在输入框中添加占位符,因为第一次它是空白的(不选择下拉选项)。所以我想设置默认占位符。我不想留下空白的下拉输入框。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
</select>
</div>
【问题讨论】:
标签:
javascript
html
angularjs
angularjs-ng-repeat
【解决方案1】:
添加一个选项
<select ng-model="selectedName" ng-options="x for x in names">
<option disabled selected value>Please Select</option>
</select>
【解决方案2】:
您可以添加一个选项
<option value="" disabled selected>Please Select</option>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["","Emil", "Tobias", "Linus"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
<option value="" disabled selected>Please Select</option>
</select>
</div>
【解决方案3】:
您可以在您的选择中设置默认值 uisng ng-init。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-init="selectedName = names[0]"
ng-model="selectedName"
ng-options="x for x in names">
</select>
</div>
【解决方案4】:
你可以这样试试。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
<option value="" selected>Please select</option>
</select>
</div>
【解决方案5】:
在此处禁用添加选项:
<option disabled selected value>Select here</option>
代码: https://codepen.io/anon/pen/YYxzxj
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
<option disabled selected value>Select here</option>
</select>
</div>