问题
I followed the instructions specified in the V1.3 documentation to have a default option in one of my selects.
Therefore in my Angular ̶1̶.̶3̶.̶1̶5̶ 1.5.7 template I have:
<div class="form-group">
<div class="col-md-12">
<select ng-model="selectedObj" class="form-control"
ng-options="obj.id as obj.name for obj in objects">
<option value="">All objects</option>
</select>
</div>
</div>
and in my controller I initialise it with:
$scope.selectedObj = '';
$scope.objects = [
{
id: '1',
name: 'A',
},
{
id: '2',
name: 'B',
},
{
id: '3',
name: 'C',
},
];
What happens is that the "All objects" option is not shown and instead the default "blank option" is shown and is only selectable the first time. The blank option is probably the one described here.
How can I make my default option work in place of the default one? What am I missing?
I've just found out the Angular version inside bower_components/angular/.bower.json
is specified as 1.5.7
as opposed to what the main bower.json
file specifies (which is 1.3.15).
May this be the cause for the seemingly weird behaviour?
回答1:
The problem is with your controller.
Don't initialize your $scope.selectedObj
.
Updated controller:
$scope.objects = [
{
id: '1',
name: 'A',
},
{
id: '2',
name: 'B',
},
{
id: '3',
name: 'C',
},
];
Here is a working example:
https://stackblitz.com/edit/angularjs-twzxrk?file=home%2Fhome.html
回答2:
Set the ng-model to null
:
̶$̶s̶c̶o̶p̶e̶.̶s̶e̶l̶e̶c̶t̶e̶d̶O̶b̶j̶ ̶=̶ ̶'̶'̶;̶
$scope.selectedObj = null;
The ng-option
directive was heavily refactored in V1.4 and many bugs removed in V1.5. For more information, see
- AngularJS Developer Guide - Migrating to V1.4 - ng-options
- AngularJS Developer Guide - Migrating to V1.5 - directives ng-options
The DEMO
angular.module('app',[])
.controller("ctrl",function($scope) {
$scope.selectedObj = null;
$scope.objects = [
{
id: '1',
name: 'A',
},
{
id: '2',
name: 'B',
},
{
id: '3',
name: 'C',
},
];
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<select ng-model="selectedObj" class="form-control"
ng-options="obj.id as obj.name for obj in objects">
<option value="">All objects</option>
</select>
</body>
来源:https://stackoverflow.com/questions/51211056/ng-options-is-hiding-the-blank-value-with-angularjs-v1-5